Lambda表达式Stream源码中的方法入门案例

初始化一个集合用作stream中的方法的测试

    /**
     * 初始化集合
     * @return
     */
    private List<Phone> getList(){
        List<Phone> list =  new ArrayList<>();
        list.add(new Phone("black", 12));
        list.add(new Phone("red", 13));
        list.add(new Phone("white", 16));
        list.add(new Phone("yellow", 4));
        list.add(new Phone("yellow", 4));
        list.add(new Phone("blue", 102));
        list.add(new Phone("black", 102));
        list.add(new Phone("black", 3));

        return list;
    }
filter根据匹配条件进行过滤
    /**
     * filter
     *  TODO 返回由该流中的元素匹配给定的断言的流
     */
    @Test
    public void test_filter(){
        List<Phone> list = getList();
        // 过滤出所有的黑色
        List<Phone> collect = list.stream().filter(p -> p.getColor().equals("黑")).collect(Collectors.toList());
        collect.forEach(System.out::println);
        // 颜色为黑色的手机获取他们的重量并加到一起
        int sum = list.stream().filter(p -> p.getColor().equals( "黑")).mapToInt(Phone::getWeight).sum();
        System.out.println(sum);
    }
distinct
    /**
     * distinct
     *  TODO 过滤重复元素
     */
    @Test
    public void test_filter_distinct(){
        List<Phone> list = getList();
        // 字段
        List<String> color = list.stream().map(Phone::getColor).distinct().collect(Collectors.toList());
        color.forEach(System.out::println);

        System.out.println("================");
        // 对象
        List<Phone> collect = list.stream().distinct().collect(Collectors.toList());
        collect.forEach(System.out::println);
    }
sorted
    /**
     * sorted
     *  TODO 排序
     *   TODO 借助stream
     */
    @Test
    public void test_sort(){
        List<Phone> list = getList();
        // 字段[不传排序参数] 去除重复 默认升序
        List<String> collect = list.stream().map(Phone::getColor).distinct().sorted().collect(Collectors.toList());
        collect.forEach(System.out::println);

        System.out.println("================");
        // 字段[不传排序参数] 去除重复 降序
        List<String> collect_01 = list.stream().map(Phone::getColor).distinct().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        collect_01.forEach(System.out::println);

        System.out.println("================");
        // 传参数-1 默认升序
        List<Integer> collect1 = list.stream().map(Phone::getWeight).sorted(Integer::compareTo).collect(Collectors.toList());
        collect1.forEach(System.out::println);

        System.out.println("================");
        // 根据重量排序 默认正序
        List<Phone> collect2 = list.stream().sorted(comparing(Phone::getWeight)).collect(Collectors.toList());
        collect2.forEach(System.out::println);

        System.out.println("================");
        // 根据重量排序 默认正序 多条件排序
        List<Phone> collect_ = list.stream().sorted(comparing(Phone::getWeight).thenComparing(Phone::getColor)).collect(Collectors.toList());
        collect_.forEach(System.out::println);

        System.out.println("================");
        // 根据重量排序 倒序
        List<Phone> collect3 = list.stream().sorted(comparing(Phone::getWeight).reversed()).collect(Collectors.toList());
        collect3.forEach(System.out::println);
    }

    /**
     * 排序 sorted
     *  TODO 不借助stream
     */
    @Test
    public void test_stream_sort(){
        List<Phone> list = getList();
        // 默认生序
        list.sort(comparing(Phone::getWeight));
        list.forEach(System.out::println);

        // 降序排列
        System.out.println("=============================");
        list.sort(comparing(Phone::getWeight).reversed());
        list.forEach(System.out::println);

        // 多条件排序
        System.out.println("=============================");
        list.sort(comparing(Phone::getWeight).reversed().thenComparing(Phone::getColor));
        list.forEach(System.out::println);

        // 源码中还有一些根据类型比较的comparingInt/comparingLong/comparingLong
        System.out.println("=============================");
        list.sort(Comparator.comparingInt(Phone::getWeight).reversed());
        list.forEach(System.out::println);
    }
peek
    /**
     * peek
     *  TODO 适用于调试,可以打印元素
     *
     */
    @Test
    public void test_peek(){
        // 过滤出长度大于3的元素,并打印 .peek(e -> System.out.println("Filtered value: " + e))适用于调试
        List<String> list = Stream.of("one", "two", "three", "four").filter(e -> e.length() > 3).peek(e -> System.out.println("======Filtered value: " + e)).collect(Collectors.toList());
        list.forEach(System.out::println);

        System.out.println("=============================");
        List<String> collect = list.stream().map(String::toUpperCase).peek(e -> System.out.println("========Mapped value: " + e)).collect(Collectors.toList());
        collect.forEach(System.out::println);
    }
limit
    /**
     * limit
     *  TODO 返回一个包含该流的元素的流,被截取的的长度不能超过指定的长度。
     */
    @Test
    public void test_limit(){
        // 排序,然后从集合中取出3个元素,并打印查看
        List<String> list = Stream.of("one", "three", "two", "four").sorted().limit(3).peek(System.out::println).collect(Collectors.toList());
        list.forEach(s -> System.out.println("遍历集合: " + s));

        // 元素的个数少于限制的数量
        System.out.println("=============================");
        List<String> collect = Stream.of("one", "three", "two", "four").limit(5).sorted().collect(Collectors.toList());
        collect.forEach(System.out::println);

        // 测试没有数据
        System.out.println("=============================");
        List<String> noEle = Stream.of("").limit(5).collect(Collectors.toList());
        noEle.forEach(System.out::println);

        System.out.println("=============================");
        List<Integer> collect1 = new ArrayList<Phone>().stream().map(Phone::getWeight).limit(10).collect(Collectors.toList());
        collect1.forEach(System.out::println);
    }
skip
    /**
     * skip
     *  TODO 丢弃流指定的前n个元素后返回该流,如果该流包涵的元素少于指定的元素的个数将会返回一个空的流
     */
    @Test
    public void test_skip(){
        // 截取前两个元素后的元素
        Stream.of("one", "three", "two", "four").skip(2).peek(System.out::println).collect(Collectors.toList());
        // 截取后为空
        System.out.println("==================");
        Stream.of("one", "three", "two", "four").skip(6).peek(System.out::println).collect(Collectors.toList());
    }
forEach和forEachOrdered
    /**
     * forEach
     *  TODO 为流中的每个元素执行一个动作
     */
    @Test
    public void test_forEach(){
        Stream.of("one", "three", "two", "four").forEach(System.out::println);
    }

    /**
     * forEachOrdered
     *  TODO 为流中的每个元素执行一个动作
     */
    @Test
    public void test_forEachOrdered(){
        // 效率高,但是无序 并行处理
        Stream.of("one", "three", "two", "four").parallel().forEach(System.out::println);
        // 可以保证顺序    顺序处理
        Stream.of("one", "three", "two", "four").parallel().forEachOrdered(System.out::println);
    }
toArray
    /**
     * toArray 不带参数
     *  TODO 返回一个数组包涵这个流的元素
     */
    @Test
    public void test_toArray(){
        // 转为Object数组
        Object[] objects = Stream.of("one", "three", "two", "four").toArray();
        for (Object object : objects) {
            System.out.println(object);
        }
    }

    /**
     * toArray(IntFunction<A[]> generator) 带有参数
     *  TODO 返回一个数组包涵这个流的元素,使用提供的{@code generator}函数分配返回的数组,以及进行分区或调整大小可能需要的任何其他数组。
     *      生成的数组的大小为过滤后的元素的个数
     */
    @Test
    public void test_toArray_(){
        List<Phone> list = getList();
        // 查询出颜色为黑色的手机,然后转为数组
        Phone[] blacks = list.stream().filter(phone -> phone.getColor().equals("black")).toArray(Phone[]::new);
        for (Phone black : blacks) {
            System.out.println(black);
        }
    }
reduce
    /**
     * reduce
     *  TODO
     *      T reduce(T identity, BinaryOperator<T> accumulator);
     *      与第一种变形相同的是都会接受一个BinaryOperator函数接口,不同的是其会接受一个identity参数,用来指定Stream循环的初始值。如果Stream为空,就直接返回该值。
     *      另一方面,该方法不会返回Optional,因为该方法不会出现null。
     */
    @Test
    public void test_reduce(){
        List<Phone> list = getList();
        // 获取不会重复的质量 identity 的初始值为0
        List<Integer> collect = list.stream().map(Phone::getWeight).distinct().peek(System.out::println).collect(Collectors.toList());
        Integer sum = collect.stream().reduce(0, (a, b) -> a+b);
        Integer sum_ = collect.stream().reduce(0, Integer::sum);
        Integer sum_1 = collect.stream().reduce(3, Integer::sum);
        System.out.println("------==== sum: " + sum);
        System.out.println("------==== sum_: " + sum_);
        System.out.println("------==== sum_1: " + sum_1);

        // 测试没有值 这个的identity初始值为1 因为为空集合,对空集合求和的结果为empty 那么就会返回初始值 1
        Integer reduce = new ArrayList<Integer>().stream().reduce(1, Integer::sum);
        System.out.println(reduce); // 1
    }

    /**
     * reduce
     *  TODO
     *      Optional<T> reduce(BinaryOperator<T> accumulator);
     */
    @SuppressWarnings("OptionalGetWithoutIsPresent")
    @Test
    public void test_reduce_1(){
        List<Phone> list = getList();
        // 获取不会重复的质量
        List<Integer> collect = list.stream().map(Phone::getWeight).distinct().peek(System.out::println).collect(Collectors.toList());
        // 求和
        Optional<Integer> reduce = collect.stream().reduce((a, b) -> a + b);
        // 求和变形
        Optional<Integer> reduce_ = collect.stream().reduce(Integer::sum);
        // 最大值
        Optional<Integer> reduce_1 = collect.stream().reduce(Integer::max);
        // 最小值
        Optional<Integer> reduce_2 = collect.stream().reduce(Integer::min);

        System.out.printf("------==== reduce: %d%n", reduce.get());
        System.out.println("------==== reduce_: " + reduce_.get());
        System.out.println("------==== reduce_1: " + reduce_1.get());
        System.out.println("------==== reduce_2: " + reduce_2.get());
    }

    /**
     * reduce
     *  TODO
     *      <U> U reduce(U identity,
     *                  BiFunction<U, ? super T, U> accumulator,
     *                  BinaryOperator<U> combiner);
     *                  第三个参数是处理并发的
     */
    @Test
    public void test_reduce_2(){

    }
max
    /**
     * max
     *  TODO
     *      通过提供的比较器返回该流中的最大的元素
     */
    @Test
    public void test_max(){
        // 获取最大值,为空就返回0
        Integer max = Stream.of(1, 2, 3, 4, 5).max(Integer::compareTo).orElse(0);
        System.out.println(max);
    }
min
    /**
     * min
     *  TODO
     *      通过提供的比较器返回该流中的最小的元素
     */
    @Test
    public void test_min(){
        // 获取最小值,为空就返回0
        Integer min = Stream.of(1, 2, 3, 4, 5).min(Integer::compareTo).orElse(0);
        System.out.println(min);
    }
count
    /**
     * count
     *  TODO 返回流中的元素的个数
     *      可能无法评估。如果没有必要的确定结果的所有元素谓语。
     *      流为空返回false,断言不做评估
     */
    @Test
    public void test_count(){
        List<Phone> list = getList();
        long count = list.stream().count();
        System.out.println(count == list.size());
    }
match相关
    /**
     * anyMatch
     * boolean anyMatch(Predicate<? super T> predicate);
     *  TODO 返回对于流中的元素是否有元素与提供的断言匹配
     *      可能无法评估。如果没有必要的确定结果的所有元素谓语。
     *      流为空返回false,断言不做评估
     */
    @Test
    public void test_anyMatch(){
        // 匹配元素
        boolean ele_0 = Stream.of("").anyMatch(Predicate.isEqual("one"));
        System.out.println("匹配元素: " + ele_0);

        // 匹配元素
        boolean ele = Stream.of("one", "three", "two", "four").anyMatch(Predicate.isEqual("one"));
        System.out.println("匹配元素: " + ele);

        // 匹配元素
        boolean ele_ = Stream.of("one", "three", "two", "four").anyMatch(Predicate.isEqual("one_"));
        System.out.println("匹配元素_: " + ele_);

        // 匹配对象
        List<Phone> list = getList();
        boolean obj = list.stream().anyMatch(Predicate.isEqual(new Phone("yellow", 4)));
        System.out.println("匹配对象: " + obj);
    }

    /**
     * allMatch
     * boolean allMatch(Predicate<? super T> predicate);
     *  TODO 返回对于流中的元素是否所有元素与提供的断言匹配
     *      可能无法评估。如果没有必要的确定结果的所有元素谓语。
     *      流为空返回true,断言不做评估
     */
    @Test
    public void test_allMatch(){
        String[] strings = new String[0];
        // 匹配元素
        boolean ele = Stream.of(strings).allMatch(Predicate.isEqual("one"));
        System.out.println("匹配元素: " + ele);

        // 匹配元素
        boolean ele_ = Stream.of("one", "two").allMatch(Predicate.isEqual("one").or(Predicate.isEqual("two")));
        System.out.println("匹配元素: " + ele_);

        // 匹配元素
        boolean ele_1 = Stream.of("one", "two").allMatch(Predicate.isEqual("one").and(Predicate.isEqual("two")));
        System.out.println("匹配元素: " + ele_1);

        // 匹配对象
        List<Phone> list = new ArrayList<>();
        boolean obj = list.stream().allMatch(Predicate.isEqual(new Phone("yellow", 4)));
        System.out.println("匹配对象: " + obj);
        // 匹配对象
        List<Phone> list_ = new ArrayList<>();
        list_.add(new Phone("yellow", 4));
        boolean obj_ = list_.stream().allMatch(Predicate.isEqual(new Phone("yellow", 4)));
        System.out.println("匹配对象_: " + obj_);
    }

    /**
     * noneMatch
     *  TODO 返回对于流中的元素是否所有元素与提供的断言不匹配
     *      可能无法评估。如果没有必要的确定结果的所有元素谓语。
     *      流为空返回true,断言不做评估
     *
     */
    @Test
    public void test_noneMatch(){
        // 匹配元素
        boolean ele = Stream.of("one1").noneMatch(Predicate.isEqual("one"));
        System.out.println("匹配元素: " + ele);
        // 匹配元素
        String[] strings = new String[0];
        boolean ele_ = Stream.of(strings).allMatch(Predicate.isEqual("one"));
        System.out.println("匹配元素_: " + ele_);

        // 匹配对象
        List<Phone> list = getList();
        boolean obj = list.stream().noneMatch(Predicate.isEqual(new Phone("yellow", 4)));
        System.out.println("匹配对象: " + obj);
    }
find相关
    /**
     * findFirst
     *  TODO 返回这个流中的第一个元素的Optional来描述这个元素
     *      如果该流为空返回一个空的Optional。如果流没有遇到顺序,则可以返回任何元素。
     */
    @Test
    public void test_findFirst(){
        List<Phone> list = getList();
        Phone first = list.stream().findFirst().orElse(null);
        System.out.println(first);
    }

    /**
     * findAny
     *  TODO 返回这个流中的第一个元素的Optional来描述这个元素
     *      如果该流为空返回一个空的Optional。如果流没有遇到顺序,则可以返回任何元素。
     *      并发情况下对于同一个流可能返回的结果不一样,但是性能很高,如果需要稳定的结果使用findFirst
     */
    @Test
    public void test_findAny(){
        List<Phone> list = getList();
        Phone any = list.stream().findAny().orElse(null);
        System.out.println(any);
    }
builder
    /**
     * builder
     *  TODO Returns a builder for a {@code Stream}.
     */
    @Test
    public void test_builder(){
        Stream<Object> build = Stream.builder()
                .add("aaa")
                .add("bbbb")
                .add("cccc").build();
        List<Object> collect = build.peek(System.out::println).collect(Collectors.toList());
        // 打印结果集
        collect.forEach(System.out::println);

    }
empty返回一个空的流
    /**
     * empty
     *  TODO Returns an empty sequential {@code Stream}.
     */
    @Test
    public void test_empty(){
        Stream<String> stream = Stream.empty();
    }

猜你喜欢

转载自blog.csdn.net/wildwolf_001/article/details/103524810
今日推荐