Java使用Stream函数对集合进行分组

 1         List<Map<String,String>> list = new ArrayList<>();
 2         Map<String,String> map1 = new HashMap<>();
 3         map1.put("name", "卢俊义");
 4         map1.put("book", "水浒传");
 5         list.add(map1);
 6         Map<String,String> map2 = new HashMap<>();
 7         map2.put("name", "镇元子");
 8         map2.put("book", "西游记");
 9         list.add(map2);
10         Map<String,String> map3 = new HashMap<>();
11         map3.put("name", "林黛玉");
12         map3.put("book", "红楼梦");
13         list.add(map3);
14         Map<String,String> map4 = new HashMap<>();
15         map4.put("name", "黑旋风");
16         map4.put("book", "水浒传");
17         list.add(map4);
18         Map<String,String> map5 = new HashMap<>();
19         map5.put("name", "太上老君");
20         map5.put("book", "西游记");
21         list.add(map5);
22         Map<String, List<Map<String, String>>> books = list.stream().collect(Collectors.groupingBy(i -> i.get("book")));
23         books.forEach((k,v) -> {
24             System.out.println(k);
25             System.out.println(v.toString());
26         });

 

posted @ 2023-07-18 18:17  大瘦猴  阅读(563)  评论(0编辑  收藏  举报