先准备一点数据:
public class User {
private Integer id;
private String type;
private String name;
private String date;
// omit setter and getter
}
User user1 = new User(1,"张三","小学", "2017-03");
User user2 = new User(2,"李四","小学", "2017-03");
User user3 = new User(3,"王五","初中", "2017-02");
User user4 = new User(4,"马六","高中", "2017-04");
User user5= new User(5,"jack","大学", "2017-04");
List<User > list = new ArrayList<>();
list.add(user1 );
list.add(user2 );
list.add(user3 );
list.add(user4 );
list.add(user5);
现在想对用户列表根据日期进行分组,得到一个map: date -> List<User>。
Java7以前也许是这样的:
List<User> userList = Arrays.asList(user1, user2, user3, user5, user4); Map<String, List<User>> groupUserMap = Maps.newHashMap(); for (User user : userList) { String month = user.getDate(); if (groupUserMap.containsKey(month)) { groupUserMap.get(month).add(user); } else { groupUserMap.put(month, Lists.newArrayList(user)); } }
有了Java8之后,一切很简单了:
Map<String, List<User>> groupUserMapOne =userList.stream().collect(Collectors.groupingBy(User::getDate));
如果想分组的List里是User的name呢:
Map<String, List<String>> userByDate = Stream.of(user1, user2, user3, user5, user4).collect(Collectors.groupingBy(User::getDate, Collectors.mapping(User::getName, Collectors.toList()))); System.out.println(userByDate);