码迷,mamicode.com
首页 > 其他好文 > 详细

关于Jdk7与Jdk8对Collections进行分组的区别

时间:2019-05-28 11:05:19      阅读:619      评论:0      收藏:0      [点我收藏+]

标签:col   pre   arraylist   mit   style   war   put   的区别   java   

先准备一点数据:

 

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);

 



关于Jdk7与Jdk8对Collections进行分组的区别

标签:col   pre   arraylist   mit   style   war   put   的区别   java   

原文地址:https://www.cnblogs.com/ZJOE80/p/10935806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!