Java8:按照对象的属性,对List集合分组
一.对象类
@Data @AllArgsConstructor public class User { private Integer age; private String name; }
二.普通写法
private List<User> users =Arrays.asList(new User(20,"张三"),new User(18,"李四"),new User(20,"王五")); @Test public void testGroup(){ Map<Integer,List<User>> userMap = new HashMap<>(); users.forEach(user->{ List<User> users = userMap.get(user.getAge()); if(users==null){ users = new ArrayList<>(); users.add(user); userMap.put(user.getAge(),users); }else{ users.add(user); } }); userMap.forEach((x,y)->{ System.out.println(x+":"+y); }); }
三.java8 stream写法:
@Test public void testGroup2(){ Map<Integer,List<User>> userMap = new HashMap<>(); users.stream().collect(Collectors.groupingBy(User::getAge,Collectors.toList())) .forEach(userMap::put); userMap.forEach((x,y)->{ System.out.println(x+":"+y); }); }
运行结果:
二.List<对象>分组成List<List<对象>>,按照某一个属性
List<List<User>>users.stream().collect( Collectors.collectingAndThen(Collectors.groupingBy(User::getAge,Collectors.toList(),map->new ArrayList<>(map.values()))) );