Collectors.groupingBy

Collectors.groupingBy根据一个或多个属性对集合中的项目进行分组

代码如下:

public class ListToMapTest {
    public static void main(String[] args) throws ParseException {
        List users = Arrays.asList(
                new User("Jack",9),
                new User("Kreas",10),
                new User("Marry",13),
                new User("Timi",14));

        Map> map=users.stream().collect(Collectors.groupingBy(User::getAge));
        Map> map1=users.stream().collect(Collectors.groupingBy(i->i.getAge()+"_"+"年龄"));
        Map> map2=users.stream().collect(Collectors.groupingBy(i->{
            if(i.getAge()<10){
                return "young";
            }else{
                return "old";
            }
        }));

        System.out.println(map);
        System.out.println(map1);
        System.out.println(map2);

    }
}

输出如下:

 

 

参考文档:https://blog.csdn.net/u014231523/article/details/10253590

你可能感兴趣的:(java,java)