java8 stream操作

发布时间 2023-09-06 20:59:36作者: 黄大虾

111

public class TestSteam {

    public static void main(String[] args) {
        Student student = new Student("段誉",18,"男");
        Student student2 = new Student("萧峰",19,"男");
        Student student3 = new Student("虚竹",20,"男");
        Student student4 = new Student("王语嫣",17,"女");
        Student student5 = new Student("阿朱",null,null);
        Student student6 = new Student("鸠摩智",45,"男");
        Student student7 = new Student("扫地僧",50,"男");
        Student student8 = new Student("段誉",48,"男");

        List<Student> list = new ArrayList();
        list.add(student);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        list.add(student5);
        list.add(student6);
        list.add(student7);
        list.add(student8);

        //过滤元素,并生成新的集合
//        List<Student> collect = list.stream().filter(ss -> ss.getGender() != null && ss.getAge() <= 20).collect(Collectors.toList());
//        for (Student o : collect) {
//            System.out.println(o.getName());
//        }

        //过滤后获取数量
//        long count = list.stream().filter(ss -> ss.getGender() != null && ss.getAge() <= 20).count();
//        System.out.println("count = " + count);

        //在流中进行循环操作
//        list.stream().filter(ss -> ss.getGender() != null && ss.getAge() <= 20).forEach(ss -> {
//            System.out.print(ss.getName());
//            System.out.print(" 年龄:" + ss.getAge());
//            System.out.println(" 性别:" + ss.getGender());
//        });



        //对流中的元素进行排序
        //方法1 studenet对象内要提前实现Comparable并重写compareTo方法即可,需要倒序的话则sorted里加上Comparator.reverseOrder()
//        list.stream().sorted(Comparator.reverseOrder()).forEach(ss->{System.out.println(ss.getName() + ss.getAge());});

        //方法2 在sorted直接实现排序方法,要倒序则接上reversed()方法即可
//        list.stream().sorted(Comparator.comparing(Student::getName).reversed()).forEach(ss->{System.out.println(ss.getName() + ss.getAge());});

        //排序字段如果可能出现空值,则要加上nullsFirst()或 nullsLast()方法指定空值放前面还是放后面
        list.stream().sorted(Comparator.comparing(Student::getAge,Comparator.nullsFirst(Integer::compareTo))).forEach(ss->{System.out.println(ss.getName() + ss.getAge());});


        List<Student> collect1 = list.stream().filter(ss -> ss.getAge() > 18).collect(Collectors.toList());

        //toMap操作
        Map<String, String> collect = list.stream().filter(ss -> ss.getGender() != null && ss.getAge() <= 20).collect(Collectors.toMap(Student::getName, Student::getGender, (oldValue, newValue) -> newValue));
        System.out.println("collect = " + collect);
    }
}