Stream流的用法【分组求和、组合排序、求极值】

先声明一个学生实体类方便使用

package com.ddtech.business.influencing_factors.test;
 

public class Student {
    
    
    private Integer no;
    private String name;
    private Integer age;
    private Double mathScore;
    private Double chineseScore;
 
    public Student(Integer no, String name, Integer age, Double mathScore, Double chineseScore) {
    
    
        this.no = no;
        this.name = name;
        this.age = age;
        this.mathScore = mathScore;
        this.chineseScore = chineseScore;
    }
 
    public Integer getNo() {
    
    
        return no;
    }
 
    public void setNo(Integer no) {
    
    
        this.no = no;
    }
 
    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;
    }
 
    public Double getMathScore() {
    
    
        return mathScore;
    }
 
    public void setMathScore(Double mathScore) {
    
    
        this.mathScore = mathScore;
    }
 
    public Double getChineseScore() {
    
    
        return chineseScore;
    }
 
    public void setChineseScore(Double chineseScore) {
    
    
        this.chineseScore = chineseScore;
    }
 
    @Override
    public String toString() {
    
    
        return "Student{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", mathScore=" + mathScore +
                ", chineseScore=" + chineseScore +
                '}';
    }

}

封装一个数组,伪造数据

package com.ddtech.business.influencing_factors.test;
 
import java.util.ArrayList;
import java.util.List;

public class StudentUtil2 {
    
    
    /**
     * 生成指定的学生类的列表,用于测试
     *
     * @return  List<Student>
     */
    public static List<Student> createStudentList() {
    
    
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student(1, "林高禄", 20, 90.5, 90.5));
        studentList.add(new Student(11, "林高禄", 20, 90.5, 90.5));
        studentList.add(new Student(1, "1林高禄", 20, 90.5, 90.5));
        studentList.add(new Student(2, "林高禄", 10, 80.0, 90.0));
        studentList.add(new Student(1, "林高禄", 30, 90.5, 90.0));
        studentList.add(new Student(1, "陈文文", 10, 100.0, 90.0));
        studentList.add(new Student(2, "陈文文", 20, 90.0, 70.0));
        studentList.add(new Student(1, "蔡金鑫", 30, 80.0, 90.0));
        return studentList;
    }
    
}

开始使用

一、求相同姓名的学生的年龄之和(姓名组合)

package com.ddtech.business.influencing_factors.test;
 
import java.util.*;
import java.util.stream.Collectors;
 

public class Demo2 {
    
    

    public static void main(String[] args) {
    
    
        // 求相同姓名的学生的年龄之和(姓名组合)
        List<Student> studentList = StudentUtil2.createStudentList();
        Map<String, List<Student>> listMap = studentList.stream().collect(Collectors.groupingBy(Student::getName, Collectors.toList()));
        System.out.println("分组后的数据:");
        listMap.forEach((k,v)->{
    
    
            System.out.println("key:"+k);
            v.forEach(System.out::println);
        });
        // 求和
        System.out.println("分组后求和:");
        listMap.forEach((k,v)->{
    
    
            System.out.print("key:"+k);
            System.out.println("--年龄求和:"+v.stream().mapToInt(Student::getAge).sum());
        });
    }
 
}

二、求相同姓名和相同编号的学生的年龄之和(姓名——编号组合)

package com.ddtech.business.influencing_factors.test;
 
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 

public class Demo3 {
    
    
    public static void main(String[] args) {
    
    
        List<Student> studentList = StudentUtil2.createStudentList();
        // 通过combination返回的字符串分组,为key,相同的学生为列表
        Map<String, List<Student>> collect = studentList.stream().collect(Collectors.groupingBy(Demo3::combination, Collectors.toList()));
        // 分组后的年龄和为
        System.out.println("分组后的年龄和为:");
        collect.forEach((key,list)-> System.out.println("key:"+key+",年龄和"+list.stream().mapToInt(Student::getAge).sum()));
 
    }
    // 编号+姓名
    private static String combination(Student s){
    
    
        return s.getNo()+s.getName()+s.getName();
    }
}

三、 按一个字段(key)分组排序,两种排序的方法

package com.ddtech.business.influencing_factors.test;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class Demo4 {
    
    
    public static void main(String[] args) {
    
    
        // 按一个字段分组排序
        List<Student> studentList = StudentUtil2.createStudentList();
        Map<Integer, List<Student>> collect =studentList.stream().collect(Collectors.groupingBy(Student::getAge));
        ArrayList<Integer> keys = new ArrayList<>();
        collect.forEach((k,v)->{
    
    
           keys.add(k);
        });
        keys.sort(Comparator.comparing(Integer::intValue));
        for (Integer key : keys) {
    
    
            System.out.println("key"+key);
            List<Student> students = collect.get(key);
            for (Student student : students) {
    
    
                System.out.println(student);
            }
        }

        //  例子:学生按编号排序,再按年龄排序
        System.out.println("第一种:直接排序");
        studentList.sort(Comparator.comparing(Student::getNo).reversed().thenComparing(Comparator.comparing(Student::getAge).reversed()));
        studentList.forEach(System.out::println);
        System.out.println("第二种:用Stream排序");
        studentList.stream()
                .sorted(Comparator.comparing(Student::getNo).reversed().thenComparing(Comparator.comparing(Student::getAge).reversed()))
                .forEach(System.out::println);
 
    }
}

四、求出学生数学分数的各个值(最大,最小,平均,总数,个数)

package com.ddtech.business.influencing_factors.test;
 
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

public class Demo5 {
    
    
    public static void main(String[] args) {
    
    
        //例子:求出学生数学分数的各个值(最大,最小,平均,总数,个数)
        List<Student> studentList = StudentUtil2.createStudentList();
        DoubleSummaryStatistics collect = studentList.stream().collect(Collectors.summarizingDouble(Student::getMathScore));
        System.out.println(collect);
        System.out.println("总分为:"+collect.getSum());
    }
}

五、综合例子:求相同年龄学生的语数总分的排名,倒序

package com.ddtech.business.influencing_factors.test;

import java.security.Key;
import java.util.*;
import java.util.stream.Collectors;


public class Demo6 {
    
    
    public static void main(String[] args) {
    
    
        // 综合例子:求相同年龄学生的语数总分的排名,倒序
        List<Student> studentList = StudentUtil2.createStudentList();
        // 先按年龄分组求出极值对象
        Map<Integer, DoubleSummaryStatistics> collect1 = studentList.stream().collect(Collectors.groupingBy(Student::getAge, Collectors.summarizingDouble(s -> s.getMathScore() + s.getChineseScore())));
        collect1.forEach((k,v)->{
    
    
            System.out.println("key:"+ k+"--v:"+v.toString());
        });
        List<DoubleSummaryStatistics> doubleSummaryStatisticsList = new ArrayList<>();
        // 遍历map把极值对象放入集合
        collect1.forEach((key, doubleSummaryStatistics) -> doubleSummaryStatisticsList.add(doubleSummaryStatistics));
        // 极值对象排序输出
        doubleSummaryStatisticsList.stream().sorted(Comparator.comparing(DoubleSummaryStatistics::getSum).reversed()).forEach(System.out::println);
        System.out.println("------------");
        // 极值对象排序输出总分
        doubleSummaryStatisticsList.stream().sorted(Comparator.comparing(DoubleSummaryStatistics::getSum).reversed()).forEach(s -> System.out.println(s.getSum()));
    }
}

【点击】文章参考地址

猜你喜欢

转载自blog.csdn.net/cst522445906/article/details/123332247
今日推荐