Java8新特性_Stream API

Java8新特性_Stream API

衣带渐宽终不悔,为伊消得人憔悴

一、Stream概述

  • Stream 是Java8中处理集合的关键抽象概念,可以对集合执行非常复杂的查找,过滤和映射数据等操作;
  • 使用 Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询;
  • 可以使用 Stream API 来并行执行操作;
  • Stream API 提供了一种高效且易于使用的处理数据的方式

注:

  • Stream 自己不会存储元素;
  • Stream 不会改变源对象; 相反,它们会返回一个持有结果的新Stream;
  • Stream 操作是延迟执行的; 这意味着它们会等到需要结果的时候,才执行;

二、Stream操作的三个步骤

1.创建Stream

  • 一个数据源(如:集合、数组),获取一个流

2.中间操作

  • 一个中间操作链,对数据源的数据进行处理

3.终止操作

  • 一旦终止操作,就执行中间操作链,并产生结果。之后不会被使用
public class TestStreamAPI {

    List<Employee> employees = Arrays.asList(
            new Employee("张三",18,1999),
            new Employee("李四",28,2999),
            new Employee("王五",38,3999),
            new Employee("赵六",48,4999),
            new Employee("田七",58,5999)
    );

    @Test
    public void test1() {
        //获取一个数据流
        Stream<Employee> employeeStream = employees.stream();
        System.out.println(employeeStream);

        //获取一个并行流
        Stream<Employee> employeeStream1 = employees.parallelStream();
        System.out.println(employeeStream1);

        //获取流的第二种方式 ——由数组创建流
        Integer[] arr = new Integer[] {1,4,5,6,7,86,9};
        Stream<Integer> stream = Arrays.stream(arr);
        Optional<Integer> first = stream.findFirst();
        System.out.println(first);

        //获取留的第三种方式——可以使用静态方法Stream.of(),即用值创建流
        Stream<String> stream1 = Stream.of("shuPush");
        System.out.println(stream1);
    }

    @Test
    public void test2() {
        //创建无限流
        //迭代的方式创建无限流
        Stream.iterate(0,(x) -> x+2).limit(10)
                .forEach(System.out :: println);

        //生成的方式产生无限流
        Stream.generate(() -> Math.random()).limit(3)
                .forEach(System.out :: println);
    }
}
/**
 * @Author: slx
 * @Date: 2019/4/10 14:37
 */
public class TestStreamAPI2 {

    List<Employee> employees = Arrays.asList(
            new Employee("张三",18,1999),
            new Employee("李四",28,2999),
            new Employee("王五",38,3999),
            new Employee("赵六",48,4999),
            new Employee("赵五",48,4999),
            new Employee("赵六",48,4999),
            new Employee("田七",58,5999)
    );

    /**
     * 筛选与切片 filter——接收 Lambda , 从流中排除某些元素。 limit——截断流,使其元素不超过给定数量。
     * skip(n) ——跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。
     * 与 limit(n) 互补
     * distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
     */
    @Test
    public void test1() {
        Stream<Employee> stream = employees.stream();
        stream.filter((e) -> {
            System.out.println("中间操作");
            return e.getAge() > 30;
        }).forEach(System.out :: println);
        System.out.println("--------------------------------");

        /**
         * 下面这一部分由于没有终止操作,所以"中间操作"这四个字并没有打印出来,只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
         */
        Stream<Employee> stream1 = employees.stream();
        stream1.filter((e) -> {
            System.out.println("中间操作");
            return e.getAge() > 30;
        });
        System.out.println("--------------------------------");

        // 必须再创建一个新流 目测是新功能的时候,不能用上面的流,否则会报流已经打开或关闭的错误
        Stream<Employee> stream2 = employees.stream();
        stream2.filter((e) -> e.getAge() > 30)
                .limit(2)
                .forEach(System.out :: println);
        System.out.println("--------------------------------");

        // skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
        Stream<Employee> stream3 = employees.stream();
        stream3.filter((e) -> e.getAge() > 30)
                .skip(1)
                .forEach(System.out :: println);
        System.out.println("--------------------------------");

        // distinct——筛选,通过流所生成元素的 hashCode() 和 equals()这样去除重复元素(意即需要重写实体类的hashcode 和equals方法)
        Stream<Employee> stream4 = employees.stream();
        stream4.filter((e) -> e.getAge() > 30)
                .distinct()
                .forEach(System.out :: println);
        System.out.println("--------------------------------");
    }

    /**
     * 映射: 1、map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
     * 2、mapToDouble(ToDoubleFunction f)) 接收一个函数作为参数,该函数会被应用到每个素上,产生一个新的
     * DoubleStream 3、mapToInt(ToIntFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的
     * IntStream。 4、mapToLong(ToLongFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的
     * LongStream 5、flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
     *
     */
    @Test
    public void test2() {

        /**
         * 1、map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
         * 把姓名的集合取出来
         * stream.map((x)->x.getName()).forEach(System.out::println);
         * 方法引用的方式写的
         */
        Stream<Employee> stream = employees.stream();
        stream.map(Employee::getName).forEach(System.out :: println);
        System.out.println("--------------------------------");



        /**
         * 2、mapToDouble(ToDoubleFunction f)) 接收一个函数作为参数,该函数会被应用到每个素上,产生一个DoubleStream
         * Stream<Person> stream1 = employees.stream();
         * stream1.mapToDouble((x)->x.getSalary())
         * .forEach(System.out::println);
         * 另一种写法 即:接受了Employee类的getSalary()方法为参数,把薪资全都取出胡来了
         */
        Stream<Employee> stream1 = employees.stream();
        stream1.mapToDouble(Employee::getSalary).forEach(System.out :: println);
        System.out.println("--------------------------------");


        /**
         * 3、mapToInt(ToIntFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。
         */
        Stream<Employee> stream2 = employees.stream();
        stream2.mapToInt(Employee::getAge).forEach(System.out :: println);
        System.out.println("--------------------------------");

        /**
         * TestStreamAPI2::filterCharacter就代表把每一个字符串("aaa","bbb"...)都进行filterCharacter()处理,
         * 这时候每个字母,都变成了一个流,而map()方法返回的也是一个流,所以返回值就成了Stream<Stream<Character>>
         */
        Stream<String> stream3 = Stream.of("aaa","bbb","ccc","ddd");
        Stream<Stream<Character>> map = stream3.map(TestStreamAPI2 :: filterCharacter);
        //用map的话还得多重遍历(sm 代表一个Stream<Character>,所以再对sm进行了遍历)
        map.forEach((sm) -> sm.forEach(System.out :: println));
        System.out.println("--------------------------------");

        /**
         * flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另一个流,
         * 然后把所有流连接成一个流(是个关键)
         */
        Stream<String> stream4 = Stream.of("aaa","bbb","ccc","ddd");
        Stream<Character> flatMap = stream4.flatMap(TestStreamAPI2::filterCharacter);
        flatMap.forEach(System.out :: println);
        System.out.println("--------------------------------");


        /**
         * map 和flatmap类似于list集合的add()方法和addAll()方法
         */
        List<Object> list = new ArrayList<>();
        List<Object> list1 = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list1.add("1");
        //add是把集合加进去了
        list1.add(list);
        System.out.println(list1);
        System.out.println("--------------------------------");

        List<Object> list2 = new ArrayList<>();
        List<Object> list3 = new ArrayList<>();
        list2.add("aaa");
        list2.add("bbb");
        list2.add("1");
        //addAll是把集合中的每一个元素加进去了
        list3.addAll(list2);
        System.out.println(list3);

    }

    //把字符串转化为字符数组流
    public static Stream<Character> filterCharacter(String string) {
        List<Character> list = new ArrayList<>();
        for (Character character : string.toCharArray()) {
            list.add(character);
        }
        return list.stream();
    }

    /**
     * sorted() 产生一个新流,其中按自然顺序 sorted(Comparator comp) 产生一个新流,其中按比较器顺序
     */
    @Test
    public void test3() {
        //sorted() 产生一个新流,其中按自然顺序
        List<String> list = Arrays.asList("aaa","bbb","ccc","ddd","eee");
        Stream<String> stream = list.stream();
        stream.sorted().forEach(System.out :: println);
        System.out.println("---------------------------------");


        employees.stream().sorted((e1,e2) -> {
            /**
             * 年龄相同按姓名排序,否则按年龄排序
             */
            if (e1.getAge() == e2.getAge()) {
                return e1.getName().compareTo(e2.getName());
            } else {
                return Integer.compare(e1.getAge(), e2.getAge());
            }
        }).forEach(System.out :: println);

    }

    /**
     * stream的终止操作(查找与匹配)
     * 1、allMatch(Predicate p) 检查是否匹配所有元素
     * 2、anyMatch(Predicate p) 检查是否至少匹配一个元素
     * 3、noneMatch(Predicate p)检查是否没有匹配所有元素
     * 4、findFirst() 返回第一个元素
     * 5、findAny() 返回当前流中的任意元素
     */
    @Test
    public void test4() {
        // allMatch(Predicate p) 检查是否匹配所有元素,即所有元素的name是赵六才返回true
        boolean b = employees.stream()
                .allMatch((e) -> e.getName().equals("赵六"));
        System.out.println(b);
        System.out.println("---------------------------------");

        // anyMatch(Predicate p) 检查是否至少匹配一个元素,只要有一个元素的name是赵六就返回true
        boolean c = employees.stream()
                .anyMatch((e) -> e.getName().equals("赵六"));
        System.out.println(c);
        System.out.println("---------------------------------");

        //noneMatch(Predicate p) 检查是否没有匹配所有元素,即 所有的元素的name都不是小刚才返回true
        boolean d = employees.stream()
                .noneMatch((e) -> e.getName().equals("小刚"));
        System.out.println(d);

        //findFirst() 返回第一个元素,返回符合条件的第一个元素
        Optional<Employee> findFirst = employees.stream().sorted(
                (e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()))
                .findFirst();
        System.out.println(findFirst.get());

        //findAny() 返回当前流中的任意元素()
        Optional<Employee> any = employees.parallelStream()
                .filter((e) -> e.getName().equals("赵六")).findAny();
        System.out.println(any);
    }


    /**
     * 1、count() 返回流中元素总数
     * 2、max(Comparator c) 返回流中最大值
     * 3、min(Comparator c)返回流中最小值
     * 4、forEach(Consumer c) 内部迭代(使用 Collection接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做
     */
    @Test
    public void test5() {

        // count() 返回流中元素总数
        long count = employees.stream().count();
        System.out.println(count);
        System.out.println("----------------------------");

        Optional<Employee> max = employees.stream().max(
                (e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary())
        );
        System.out.println("最高工资的员工为: " + max);
        System.out.println("----------------------------");

        Optional<Employee> min = employees.stream().min(
                (e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary())
        );
        System.out.println("最低工资的员工为: " + min);
    }

    /**
     * 归约
     * 1、reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值,返回 T
     * 2、reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
     */
    @Test
    public void test6() {
        // reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值,返回 T
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        /**
         * 先把0作为了x,y是流中的第一个元素 相加得1,然后1作为x,流中的第二个元素作为y,就这样,依次加下去。
         */
        Integer reduce = list.stream().reduce(0,(x,y) -> x+y);
        System.out.println(reduce);
        System.out.println("----------------------------");

        // reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
        /**
         * 可以看出两个reduce方法返回的并不一样,因为第一个reduce方法有初始值,最后所得的值肯定不会为空,而第二种情况则有可能会为空,所以返回值为跑optional
         */
        Optional<Double> reduce2 = employees.stream().map(Employee::getSalary)
                .reduce(Double :: sum);
        System.out.println(reduce2);

    }

    /**
     * 收集: collect(Collector c) 将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
     */
    @Test
    public void test7() {
        //把人员名字放到一个list中去
        List<String> collect = employees.stream().map(Employee::getName)
                .collect(Collectors.toList());
        System.out.println(collect);
        System.out.println("----------------------------");

        //把人员的名字放到一个hashset中去(会自动去重)
        HashSet<String> collect2 = employees.stream().map(Employee::getName)
                .collect(Collectors.toCollection(HashSet::new));
        System.out.println(collect2);
        System.out.println("----------------------------");

        //计数
        Long l = employees.stream().collect(Collectors.counting());
        System.out.println(l);
        System.out.println("----------------------------");

        //取所有人员薪资的平均值
        Double double1 = employees.stream()
                .collect(Collectors.averagingDouble((e) -> e.getSalary()));
        System.out.println("所有员工薪资的平均值:" + double1);
        System.out.println("-----------------------------");

        //把所有人的姓名拼接成一个字符串
        String collect5 = employees.stream().map(Employee::getName)
                .collect(Collectors.joining());
        System.out.println(collect5);
        System.out.println("----------------------------");

        //找出所有人中薪资最少的一个员工的信息。
        Optional<Employee> optional = employees.stream().collect(Collectors.minBy(
                (e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary())
        ));
        System.out.println(optional);
        System.out.println("----------------------------");
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值