转自:https://www.cnblogs.com/wwjj4811/p/13246031.html
1、对象类
@Data @AllArgsConstructor public class User { private Integer age; private String name; }
2、普通写法
//构建的list数据
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); }); }
3、Java8 写法
@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); }); }
4、运行结果