【Java】list根据某一条件进行分组
集合中为对象,根据对象中的某一属性值分组
public static void main(String[] args){ List<User> list = new ArrayList<>(); User user1 = new User("1", "张三1", "10"); User user2 = new User("2", "张三2", "10"); User user3 = new User("2", "张三3", "10"); User user4 = new User("4", "张三4", "11"); User user5 = new User("5", "张三5", "11"); User user6 = new User("6", "张三6", "11"); User user7 = new User("7", "张三7", "12"); User user8 = new User("8", "张三8", "12"); User user9 = new User("9", "张三9", "12"); list.add(user1); list.add(user2); list.add(user3); list.add(user4); list.add(user5); list.add(user6); list.add(user7); list.add(user8); list.add(user9); List<List<User>> groupList = new ArrayList<>(); list.stream().collect(Collectors.groupingBy(User::getAge,Collectors.toList())) .forEach((age,fooListByAge)->{ groupList.add(fooListByAge); }); groupList.forEach((userList)->{ System.out.println(userList.size()); userList.forEach((user)->System.out.println(user)); }); }
注意:
list.stream().collect(Collectors.groupingBy(User::getAge,Collectors.toList()))
.forEach((age,fooListByName)->{
groupList.add(fooListByName);
});
此句中的User::getAge
getAge 为对象中某属性的get方法