Java 8 stream的详细用法

话不多说,直接看代码演示

 

/**
 * @description: stream 练习
 * @author: hwx
 * @date: 2022/02/10
 **/
public class stream {
   static class  Person {
        private String name;  // 姓名
        private int salary; // 薪资
        private int age; // 年龄
        private String sex; //性别
        private String area;  // 地区

        // 构造方法
        public Person(String name, int salary, int age,String sex,String area) {
            this.name = name;
            this.salary = salary;
            this.age = age;
            this.sex = sex;
            this.area = area;
        }

       public Person(String name, int salary, String sex, String area) {
           this.name = name;
           this.salary = salary;
           this.sex = sex;
           this.area = area;
       }


       // 省略了get和set,请自行添加


        public String getName() {
            return name;
        }

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

        public int getSalary() {
            return salary;
        }

        public void setSalary(int salary) {
            this.salary = salary;
        }

        public int getAge() {
            return age;
        }

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

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        public String getArea() {
            return area;
        }

        public void setArea(String area) {
            this.area = area;
        }

       @Override
       public String toString() {
           return "Person{" +
                   "name='" + name + '\'' +
                   ", salary=" + salary +
                   ", age=" + age +
                   ", sex='" + sex + '\'' +
                   ", area='" + area + '\'' +
                   '}';
       }
   }

    public static void main(String[] args) {
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, "male", "New York"));
        personList.add(new Person("Tom", 8800, "male", "New York"));
        personList.add(new Person("Jack", 7000, "male", "Washington"));
        personList.add(new Person("Lily", 7800, "female", "Washington"));
        personList.add(new Person("Anni", 8200, "female", "New York"));
        personList.add(new Person("Owen", 9500, "male", "New York"));
        personList.add(new Person("Alisa", 7900, "female", "New York"));

        //遍历输出符合条件的元素
        personList.stream().filter(e -> e.salary > 8000).forEach(System.out::println);
        //筛选薪资大于8000的
        List<Person> collect = personList.stream().filter(e -> e.salary > 8000).collect(Collectors.toList());
//        List<Person> collect22 = personList.stream().filter(e -> e::getSalary>8000).collect(Collectors.toList());
        Set<Person> collect1 = personList.stream().filter(e -> e.salary > 8000).collect(Collectors.toSet());
        //去重
        Map<String, Integer> collect2 = personList.stream().filter(e -> e.salary > 8000).collect(Collectors.toMap(e -> e.name, e -> e.salary,(a1,a2)->a2));
        //.map用法
        List<String> collect3 = personList.stream().filter(e -> e.salary > 8000).map(e -> e.name).collect(Collectors.toList());

        // 匹配第一个
        Optional<Person> first = personList.stream().filter(e -> e.salary > 8000).findFirst();
        // 匹配任意(适用于并行流)
        Optional<Person> first1 = personList.parallelStream().filter(e -> e.salary > 8000).findFirst();
        // 是否包含符合特定条件的元素
        boolean b = personList.stream().anyMatch(e -> e.salary > 8000);

        System.out.println(collect);
        System.out.println(collect1);
        System.out.println(collect2);
        System.out.println(collect3);
        System.out.println("匹配第一个"+first);
        System.out.println("匹配任意(适用于并行流)"+first1);
        System.out.println("是否包含符合特定条件的元素"+b);

        //筛选出名字最长的
        Optional<Person> max = personList.stream().max(Comparator.comparing(e -> e.name.length()));
        //筛选出工资最高的
        Optional<Person> max1 = personList.stream().max(Comparator.comparing(e -> e.salary));
        System.out.println("筛选出名字最长的"+max);
        System.out.println("筛选出工资最高的"+max1);

        //筛选出工资大于8000的总人数
        long count = personList.stream().filter(e -> e.salary > 8000).count();
        System.out.println("筛选出工资大于8000的总人数"+count);

        String[] strArr = { "abcd", "bcdd", "defde", "fTr" };
        //英文字符串数组的元素全部改为大写
        List<String> collect4 = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());
        System.out.println("英文字符串数组的元素全部改为大写"+collect4);

        List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);
        //整数数组每个元素+3
        List<Integer> collect5 = intList.stream().map(e -> e + 3).collect(Collectors.toList());
        System.out.println("整数数组每个元素+3"+collect5);

        //将员工的薪资全部增加1000。
        List<Integer> collect6 = personList.stream().map(e -> e.salary + 1000).collect(Collectors.toList());
        System.out.println("将员工的薪资全部增加1000"+collect6);
        List<Person> collect7 = personList.stream().map(e -> {
            Person person = new Person(e.name, e.salary, e.sex, e.area);
            person.setSalary(person.salary + 1000);
            return person;
        }).collect(Collectors.toList());
        System.out.println("(不改变原先结构)将员工的薪资全部增加1000"+collect7);
       /* List<Person> collect8 = personList.stream().map(e -> {
            e.setSalary(e.salary + 1000);
            return e;
        }).collect(Collectors.toList());
        System.out.println("(不改变原先结构)将员工的薪资全部增加1000(原先的list被改变)"+collect8);*/

        //将两个字符数组合并成一个新的字符数组
        List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7");
        List<String> collect9 = list.stream().flatMap(e -> {
            // 将每个元素转换成一个stream
            String[] split = e.split(",");
            Stream<String> s2 = Arrays.stream(split);
            return s2;
        }).collect(Collectors.toList());
        System.out.println("将两个字符数组合并成一个新的字符数组"+collect9);


        //求所有员工的工资之和
        Optional<Integer> reduce = personList.stream().map(Person::getSalary).reduce(Integer::sum);
        System.out.println("求所有员工的工资之和"+reduce);
        Integer reduce1 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> sum1 + sum2);
        System.out.println("求所有员工的工资之和"+reduce1);
        Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);
        System.out.println("求所有员工的工资之和"+sumSalary3);

        // 求员工总数
        Long collect10 = personList.stream().collect(Collectors.counting());
        System.out.println("求员工总数"+collect10);
        // 求平均工资
        Double collect11 = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
        System.out.println("求平均工资"+collect11);
        // 求最高工资
        Optional<Integer> collect12 = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
        System.out.println("求最高工资"+collect12);
        // 求工资之和
        Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
        System.out.println("员工工资总和:" + sum);
        // 一次性统计所有信息
        DoubleSummaryStatistics collect13 = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
        System.out.println("员工工资所有统计:" + collect13);

        //分组
        // 将员工按薪资是否高于8000分组
        Map<Boolean, List<Person>> collect8 = personList.stream().collect(Collectors.partitioningBy(e -> e.getSalary() > 8000));
        System.out.println("将员工按薪资是否高于8000分组"+collect8);
        // 将员工按性别分组
        Map<String, List<Person>> collect14 = personList.stream().collect(Collectors.groupingBy(Person::getSex));
        System.out.println("将员工按性别分组"+collect14);
        // 将员工先按性别分组,再按地区分组
        Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
        System.out.println("将员工先按性别分组,再按地区分组"+group2);

        //接合
        String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));
        System.out.println("所有员工的姓名:" + names);

        //排序
        // 按工资升序排序(自然排序)
        List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
                .collect(Collectors.toList());
        System.out.println("按工资升序排序(自然排序)"+newList);
        // 按工资倒序排序
        List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
                .map(Person::getName).collect(Collectors.toList());
        System.out.println("按工资倒序排序"+newList);
        // 先按工资再按年龄升序排序
        List<String> newList3 = personList.stream()
                .sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)
                .collect(Collectors.toList());
        System.out.println("先按工资再按年龄升序排序:" + newList3);
        // 先按工资再按年龄自定义排序(降序)
        List<String> newList4 = personList.stream().sorted((p1, p2) -> {
            if (p1.getSalary() == p2.getSalary()) {
                return p2.getAge() - p1.getAge();
            } else {
                return p2.getSalary() - p1.getSalary();
            }
        }).map(Person::getName).collect(Collectors.toList());
        System.out.println("先按工资再按年龄自定义降序排序:" + newList4);


        String[] arr1 = { "a", "b", "c", "d" };
        String[] arr2 = { "d", "e", "f", "g" };

        Stream<String> stream1 = Stream.of(arr1);
        Stream<String> stream2 = Stream.of(arr2);
        // concat:合并两个流 distinct:去重
        List<String> newList8 = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
        // limit:限制从流中获得前n个数据
        List<Integer> collect88 = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
        // skip:跳过前n个数据
        List<Integer> collect888 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());

        System.out.println("流合并:" + newList8);
        System.out.println("limit:" + collect88);
        System.out.println("skip:" + collect888);

    }
}

 

posted @ 2022-02-15 15:00  jiuchengi  阅读(172)  评论(0编辑  收藏  举报