一.对象类
@Data
@AllArgsConstructor
public class User {
private Integer age;
private String name;
}
二.普通写法
private List users =Arrays.asList(new User(20,"张三"),new User(18,"李四"),new User(20,"王五"));
@Test
public void testGroup(){
Map> userMap = new HashMap<>();
users.forEach(user->{
List 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> userMap = new HashMap<>();
users.stream().collect(Collectors.groupingBy(User::getAge,Collectors.toList()))
.forEach(userMap::put);
userMap.forEach((x,y)->{
System.out.println(x+":"+y);
});
}
运行结果: