一.對象類
@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()))) );
