Java新特性玩转JDK8之收集器 group by分组

DBC 709 0
分组 Collectors.groupingBy()

public static Collector>> groupingBy(Function classifier) { return groupingBy(classifier, toList());
}

小例子
public class Main {
    public static void main(String[] args) throws Exception {
        List<Student> students = Arrays.asList(new Student("广东", 23), new Student("广东", 24),
                new Student("广东", 23),
                new Student("北京", 22), new Student("北京", 20),
                new Student("北京", 20), new Student("海南", 25));

        Map<String,List<Student>> listMap =  students.stream().collect(Collectors.groupingBy(obj->obj.getProvince()));

        listMap.forEach((key,value)->{

            System.out.println("=======");
            System.out.println(key);
            value.forEach(obj->{
                System.out.println(obj.getAge());
            });

        });

    }
}


class Student {
    private int age;

    private String province;


    public Student(String province, int age) {
        this.province = province;
        this.age = age;
    }

    public Student() {
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }
}
控制台输出
Java新特性玩转JDK8之收集器 group by分组插图

发表评论 取消回复
表情 图片 链接 代码

分享