How to increase by group

There is a table and now add a new column - 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

Now I want to set the sort_num values ​​as shown below

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 code requirement above:

    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);
    }

I want to know if can Java8simplify the code above?

PS. Use mysqlto implement this requirement.

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;
+4
source share
2 answers

The best approach is to stick with your simple extended loop. I don’t think you can come up with one solution Stream, since you need to have intermediate values. How:

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))
);
+2
source

, . , :

Map<Integer, AtomicInteger> orders = new ConcurrentHashMap<>();
fooList.stream().forEachOrdered(foo -> {
    orders.putIfAbsent(foo.getLevel(), new AtomicInteger());
    foo.setOrder(orders.get(foo.getLevel()).incrementAndGet());
});

, .

0

Source: https://habr.com/ru/post/1672669/


All Articles