有一个表,现在添加一个新列 -- sort_num int default 0
id level sort_num
1 1 0
2 1 0
3 2 0
4 2 0
5 2 0
6 3 0
7 3 0
8 3 0
9 3 0
现在我想设置 sort_num 值,如下所示
id level sort_num
1 1 1
2 1 2
3 2 1
4 2 2
5 2 3
6 3 1
7 3 2
8 3 3
9 3 4
上面要求的Java代码实现是
int sortNum = 0;
int currentLevel = fooList.get(0).getLevel();
for (RuleConf foo : fooList) {
if(currentLevel != foo.getLevel()){
sortNum = 0;
currentLevel = foo.getLevel();
}
foo.setSortNum(++sortNum);
}
我想知道是否
Java8
可以简化上面的代码吗?附注。使用
mysql
实现这一要求set @index:=0; update t set sort_num = (@index:=@index+1) where level = 1 order by id;
set @index:=0; update t set sort_num = (@index:=@index+1) where level = 2 order by id;
set @index:=0; update t set sort_num = (@index:=@index+1) where level = 3 order by id;
最佳答案
最好的方法是坚持使用简单的增强 for 循环。我认为不可能想出一个Stream
解决方案,因为您需要有中间值。喜欢:
Map<Integer, List<RuleConf>> levels = fooList.stream()
.collect(Collectors.groupingBy(RuleConf::getLevel));
levels.values().forEach(v ->
IntStream.range(0, v.size()).forEach(i -> v.get(i).setSortNum(i + 1))
);
关于java-8 - 如何按组递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42886741/