How to assign incremental values to lists in Java 8
•
Java
Suppose you have a list of objects The list is sorted by one or more fields of the object So according to the sort list, I want to set the field of the object with incremental value
public class ObjectTest {
int id;
int userId;
int code;
}
As mentioned above, objecttest, any user has its own code There is an objecttest list
List<ObjectTest> objTests;
It sort:
objTests.sort(Comparator.comparing(DataSet::getUserId).thenComparing(DataSet::getCode));
Therefore, after sorting by userid and code, I want to set the value from 1 to any user has its own code When the userid changes, the increment value is reset to 1 again
If you have the following objecttest set
id userId code
--------------------------------
100 5
200 6
100 7
200 9
200 10
100 2
After explaining the above scenario, the following sets will be:
id userId code 1 100 2 2 100 5 3 100 7 1 200 6 2 200 9 3 200 10
Can I use lambda expressions in Java
Solution
Some things should work:
List<ObjectTest> resultSet =
objTests.stream()
.sorted(Comparator.comparing(ObjectTest::getUserId).thenComparing(ObjectTest::getCode))
.collect(Collectors.groupingBy(ObjectTest::getUserId,LinkedHashMap::new,Collectors.toList()))
.values()
.stream()
.map(e -> {
IntStream.range(0,e.size())
.forEach(i -> e.get(i).setId(i + 1));
return e;
})
.flatMap(Collection::stream)
.collect(Collectors.toList());
Note that I haven't compiled this code yet
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
