对list进行分组
对map集合分组
以id分组,将id相同的放在一起
List<Map<String, Object>> list = Mapper.find();
Map<Object, List<Map<String, Object>>> collect =
list.stream().collect(Collectors.groupingBy(d -> d.get("id")));
Set<Object> keySet = collect.keySet();
for (Object id : keySet) {
Map<String, Object> map1 = new HashMap<>();
List<Map<String, Object>> list2 = collect.get(id);
for (Map<String, Object> map : list2) {
}
}
对实体类进行分组
List
siteEntityList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
SiteEntity entity = new SiteEntity();
entity.setId(i);
entity.setName(“a” + i);
siteEntityList.add(entity);
}
for (int i = 0; i < 5; i++) {
SiteEntity entity = new SiteEntity();
entity.setId(i);
entity.setName(“b” + i);
siteEntityList.add(entity);
}
for (int i = 0; i < 5; i++) {
SiteEntity entity = new SiteEntity();
entity.setId(i);
entity.setName(“c” + i);
siteEntityList.add(entity);
}
Map<Integer, List> collect1 =siteEntityList.stream().collect(Collectors.groupingBy(SiteEntity::getId));
Iterator<Map.Entry<Integer, List>> iterator1 =collect1.entrySet().iterator();
while (iterator1.hasNext()) {
Map.Entry<Integer, List> next =iterator1.next();
Listvalue = next.getValue();
System.out.println(“——-“);
value.forEach(e -> System.out.println(e));
}
对实体类中的属性进行分组
Map<Integer, List
> collect2= siteEntityList.stream().collect(Collectors.groupingBy(SiteEntity::getId, Collectors.mapping(SiteEntity::getName, Collectors.toList())));
Iterator<Map.Entry<Integer, List>> iterator2 =collect2.entrySet().iterator();
while (iterator2.hasNext()) {
Map.Entry<Integer, List> next = iterator2.next();
Listvalue = next.getValue();
System.out.println(“———–”);
value.stream().forEach(System.out::println);
}
}