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

Posted zjoe80

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于Jdk7与Jdk8对Collections进行分组的区别相关的知识,希望对你有一定的参考价值。

先准备一点数据:

 

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进行分组的区别的主要内容,如果未能解决你的问题,请参考以下文章

JDK8:找回 JDK7 查找 javadoc

JDK7与JDK8中HashMap的实现

类的加载时机反射模板设计jdk7/jdk8新特性(二十六)

源码之ConcurrentHashMap

win环境下jdk7与jdk8共存问题

win环境下jdk7与jdk8共存问题