JAVA8 collect 使用

List<Student> studentList = Lists.newArrayList(new Student("路飞", 22, 175), new Student("红发", 40, 180),
                new Student("白胡子", 50, 185), new Student("白胡子", 60, 185));
        //最大值
        Optional<Student> maxStudent = studentList.stream().max(Comparator.comparingInt(Student::getHeight));
        //最小值
        Optional<Student> minStudent = studentList.stream().min(Comparator.comparingInt(Student::getHeight));
        //平均值
        Double avgAge = studentList.stream().collect(Collectors.averagingInt(Student::getAge));
        //统计,包括数量,和,最大最小值
        IntSummaryStatistics summaryStatistics = studentList.stream().collect(Collectors.summarizingInt(Student::getAge));
        long count = summaryStatistics.getCount();
        int max = summaryStatistics.getMax();
        int min = summaryStatistics.getMin();
        long sum = summaryStatistics.getSum();
        //连接收集器
        //直接连接
        String join1 = studentList.stream().map(Student::getName).collect(Collectors.joining());
        //逗号
        String join2 = studentList.stream().map(Student::getName).collect(Collectors.joining(","));
        //toList
        List<String> nameList = studentList.stream().map(Student::getName).collect(Collectors.toList());
        //toSet
        Set<String> nameSet = studentList.stream().map(Student::getName).collect(Collectors.toSet());
        //去重
        List<Student> uniqueStudentList = studentList.stream().distinct().collect(Collectors.toList());
        //按属性去重
        List<Student> attrUniqueStudentList = studentList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));

        //toMap
        Map<String, Integer> studentMap = studentList.stream().collect(Collectors.toMap(Student::getName, Student::getAge));
public class Student {
    private String name;
    private Integer age;
    private Integer height;


    public Student(String name, Integer age, Integer height) {
        this.name = name;
        this.age = age;
        this.height = height;
    }

    public Student() {
    }

    public Integer getHeight() {
        return height;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
posted @   abowu  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示