java 对象集合按某字段分组并且每100条一组
可以使用 Java 8 的 Stream API 来对集合进行分组和分批操作。假设我们有一个 Student 类,其中有两个属性:name 和 score。我们需要将 Student 对象按照 score 属性进行分组,并且每 100 条数据一组,可以按照以下方式实现:
List<Student> students = new ArrayList<>(); // 假设有一些 Student 对象
// 按照 score 属性进行分组,并且每 100 条数据一组
Map<Integer, List<List<Student>>> groups = students.stream()
.collect(Collectors.groupingBy(Student::getScore))
.entrySet().stream()
.collect(Collectors.groupingBy(e -> e.getKey() / 100))
.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> e.getValue().stream().map(Map.Entry::getValue).collect(Collectors.toList())
));
上述代码将 Student 对象按照 score 属性进行第一次分组,然后按照 score 的值除以 100 进行第二次分组,最后将结果转换为一个 Map,其中 key 是分组的序号,value 是一个 List,其中包含 100 条 Student 对象。注意,最后一组可能不足 100 条数据
原文地址: https://www.cveoy.top/t/topic/fgTE 著作权归作者所有。请勿转载和采集!