导入包:
import static java.util.stream.Collectors.counting; import static java.util.stream.Collectors.groupingBy;
java代码:
/** * 分组 * @Author: Mr.li * @Date: 2020/9/8 */ @Test public void demo5() { List<User> list = new ArrayList<User>() { { add(new User("妮妮", "1999/01/01", 12,"男")); add(new User("哪儿能", "1999/01/01", 55,"女")); add(new User("爱思", "1999/01/01", 66,"男")); add(new User("依依", "1999/01/01", 77,"女")); } }; /*将所有人分为老年人、中年人、青年人*/ /*Map<String, List<User>> result = list.stream() .collect(groupingBy((user) -> { if (user.getAge() > 60) return "老年人"; else if (user.getAge() > 40) return "中年人"; else return "青年人"; })); System.out.println(result);*/ /*将所有人分为老年人、中年人、青年人,并且将每个小组再分成:男女两组。*/ /*Map<String, Map<String, List<User>>> result1 = list.stream() .collect(groupingBy((user) -> { if (user.getAge() > 60) return "老年人"; else if (user.getAge() > 40) return "中年人"; else return "青年人"; }, groupingBy(User::getSex))); System.out.println(result1);*/ Map<String, Long> result2 = list.stream() .collect(Collectors.groupingBy((person) -> { if (person.getAge() > 60) return "老年人"; else if (person.getAge() > 40) return "中年人"; else return "青年人"; }, counting())); System.out.println(result2); }
result: