Java8 new features-Stream API combat

Java 8 new features of Stream API combat

table of Contents

1. Stream overview

2. The creation of Stream

3. Use of Stream

The employee class used in the case, this is the employee class used in the following case:

3.1 Traverse and match (foreach, find, match)

3.2 Filter

3.3 Aggregation (max, min, count)

3.4 Mapping (map, flatMap)

3.5 Reduce (reduce). map-reduce operation.

3.6 Collect

3.6.1 Collection (toList, toSet, toMap)

3.6.2 Statistics (count, averaging)

3.6.3 Grouping and partitioning (partitioningBy, groupingBy)

3.6.4 Joining

3.7 sorted

3.8 Extraction and combination

4. Java has built-in 4 core functional interfaces

5. Refer to the wiki, thanks


 

1. Stream overview

There are two most important upgrades in Java 8. The first is the Lambda expression, and the other is the Steam API expression. Stream is a key abstract concept for processing collections in Java 8. It can specify the operations you want to perform on the collection, which can be various operations such as searching, filtering, and mapping data. Using Stream API to operate on collection data is similar to using SQL to perform database queries. In short, the Stream API provides an efficient and easy-to-use data processing method.

Stream It can be created by an array or a collection, and there are two types of operations on the stream:

(1) Intermediate operation: Each intermediate operation returns a new stream, and there can be multiple intermediate operations.

(2) Termination operation: Each flow can only be terminated once, and the flow cannot be used again after the termination operation. Terminating the operation will produce a new set or value.

In addition, Stream there are the following features:

(1) Stream does not store data, but calculates data according to specific rules, and generally outputs the result.

(2) Stream does not change the data source, and usually generates a new set or a value.

(3) Stream has delayed execution characteristics (ie, lazy operations), and only when the termination operation is called, a series of intermediate operations will be executed in one mind.

2. The creation of Stream

StreamCan be created by collection or array.

1. java.util.Collection.stream() Create a stream with a collection through a  method

List<String> list = Arrays.asList("a", "b", "c");
// 创建一个顺序流
Stream<String> stream = list.stream();
// 创建一个并行流
Stream<String> parallelStream = list.parallelStream();

2. How to use java.util.Arrays.stream(T[] array)an array to create a stream

int[] array={1,3,5,6,8};
IntStream stream = Arrays.stream(array);

3. StreamThe static method used to create a stream:Stream.of()、Stream.iterate()、Stream.generate()

Stream<Integer> stream00 = Stream.of(1, 2, 3);
stream00.forEach(System.out::println); //1 2 3

Stream<Integer> stream11 = Stream.iterate(0, (x) -> x + 2).limit(4);
stream11.forEach(System.out::println); //0 2 4 6

Stream<Double> stream33 = Stream.generate(Math::random).limit(3);
stream33.forEach(System.out::println);// 0.6796156909271994 0.1914314208854283 0.8116932592396652

stream And  parallelStream simple to distinguish:  streama sequence flow convection by the main thread in order to perform operations, and parallelStreamis parallel streams internally-threaded parallel execution of multiple operating convection mode, but only in the data processing flow in any sequence. For example, filter the odd numbers in the collection, the processing of the two is different. If the amount of data in the stream is large enough, the parallel stream can speed up processing. In addition to creating parallel streams directly, you can also parallel()convert sequential streams into parallel streams:

Optional<Integer> findFirst = list.stream().parallel().filter(x->x>6).findFirst();

3. Use of Stream

Before using the stream, to understand a concept: Optional .

OptionalA class is a nullcontainer object that can be used . If the value exists, the isPresent()method will return true, and calling the get()method at this time will return the value in the object. For a more detailed description, please see: Novice Tutorial Java 8 Optional Class

The employee class used in the case, this is the employee class used in the following case:

public class Person implements Serializable {
    private static final long serialVersionUID = 5675706507473016778L;
    private String name;    // 姓名
    private int salary;     // 薪资
    private int age;        // 年龄
    private String sex;     // 性别
    private String area;    // 地区
    public Person() {
    }
    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;
    }
}

3.1 Traverse and match (foreach, find, match)

StreamIt also supports traversal and matching elements of similar collections, but Streamthe elements in it Optionalexist in types. StreamThe traversal, matching and searching of is very simple.

        List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 1, 2);
        //遍历输出符合条件的元素
        list.stream()
                .filter(Objects::nonNull)
                .filter(x -> x > 6)
                .forEach(y -> System.out.print(y + "  "));
        System.out.println();
        System.out.println("===================================");

        //匹配第一个
        Optional<Integer> findFirst = list.stream()
                .filter(Objects::nonNull)
                .filter(x -> x > 6)
                .findFirst();
        System.out.println("匹配第一个值:" + (findFirst.isPresent() ? findFirst.get() : -1));
        System.out.println("===================================");

        //匹配任意一个
        Optional<Integer> findAny = list.stream()
                .filter(Objects::nonNull)
                .filter(x -> x > 6)
                .findAny();
        System.out.println("匹配任意一个值:" + (findAny.isPresent() ? findAny.get() : -1));
        System.out.println("===================================");

        //是否包含符合特定条件的元素
        boolean anyMatch = list.stream()
                .filter(Objects::nonNull)
                .anyMatch(x -> x > 16);
        System.out.println("是否存在大于6的值:" + anyMatch);
        System.out.println("===================================");

3.2 Filter

Filtering is to check the elements in the Stream stream according to certain rules, and extract the elements that meet the conditions into the new stream.

        //案例一:筛选出Integer集合中大于7的元素,并打印出来
        list.stream()
                .filter(Objects::nonNull)
                .filter(x -> x > 7)
                .forEach(y -> System.out.print(y + "  "));
        System.out.println();
        System.out.println("===================================");

        //案例二: 筛选员工中工资高于8000的人,并形成新的集合。 形成新集合依赖collect(收集),后文有详细介绍。
        List<Person> personList = Arrays.asList(
                new Person("Tom", 8900, 23, "male", "New York"),
                new Person("Jack", 7000, 25, "male", "Washington"),
                new Person("Lily", 7800, 21, "female", "Washington"),
                new Person("Anni", 8200, 24, "female", "New York"),
                new Person("Owen", 9500, 25, "male", "New York"),
                new Person("Alisa", 7900, 26, "female", "New York"),
                null
        );
        List<String> nameList = personList.stream()
                .filter(Objects::nonNull)
                .filter(x -> x.getSalary() > 8000)
                .map(Person::getName)
                .collect(Collectors.toList());
        System.out.println("高于8000的员工姓名:" + nameList);
        System.out.println("===================================");

3.3 Aggregation (max, min, count)

max, min, count These words we used them in mysql statistical data. These concepts and usage are also introduced in the Java stream API, which greatly facilitates our data statistics work on collections and arrays.

        //案例一:获取String集合中最长的元素。
        List<String> stringList = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
        Optional<String> maxLength = stringList.stream()
                .filter(Objects::nonNull)
                .max(Comparator.comparing(String::length));
        System.out.println("最长的字符串:" + (maxLength.isPresent() ? maxLength.get() + "的长度=" + maxLength.get().length() : -1));

        //案例二:获取Integer集合中的最大值。
        List<Integer> integers = Arrays.asList(7, 6, 9, 4, 11, 6);
        //(1)自然排序
        Optional<Integer> maxInteger = integers.stream()
                .filter(Objects::nonNull)
                .max(Integer::compareTo);
        System.out.println("自然排序的最大值:" + (maxInteger.isPresent() ? maxInteger.get() : -1));

        //(2)自定义排序
        Optional<Integer> maxInteger2 = integers.stream()
                .filter(Objects::nonNull)
                .max((o1, o2) -> o1 > o2 ? 1 : (o1 < o2 ? -1 : 0));
        System.out.println("自定义排序的最大值:" + (maxInteger2.isPresent() ? maxInteger2.get() : -1));

        //案例三:获取员工工资最低的人。
        Optional<Person> maxSalaryPerson = personList.stream()
                .filter(Objects::nonNull)
                .min(Comparator.comparing(Person::getSalary));
        System.out.println("员工工资最低值:" + maxSalaryPerson.get().getSalary());

        //案例四:计算Integer集合中大于6的元素的个数。
        List<Integer> integers2 = Arrays.asList(7, 6, 9, 4, 11, 6);
        long count = integers2.stream()
                .filter(Objects::nonNull)
                .filter(x -> x > 6).count();
        System.out.println("integers2中大于6的元素个数:" + count);
        System.out.println("===================================");

3.4 Mapping (map, flatMap)

Mapping can map elements of one stream to another stream according to certain mapping rules, which can be divided into map mapping and flatMap mapping.

(1) map: Receive a function as a parameter, the function will be applied to each element, and map it into a new element.

(2) flatMap: Receive a function as a parameter, convert each element in the stream into another stream, and then connect all the streams into one stream.

 //案例一:英文字符串数组的元素全部改为大写。整数数组每个元素+3。
        String[] strArr = {"abcd", "bcdd", "defde", "fTr"};
        List<String> strList = Arrays.stream(strArr)
                .filter(Objects::nonNull)
                .map(String::toUpperCase)
                .collect(Collectors.toList());
        System.out.println("每个元素转为大写:" + strList);

        List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);
        List<Integer> intListNew = intList.stream()
                .filter(Objects::nonNull)
                .map(x -> x + 3)
                .collect(Collectors.toList());
        System.out.println("每个元素+3后:" + intListNew);

        //案例二:将员工的薪资全部增加1000。
        //方法1:不改变原来员工集合的方式(不改变数据源)
        List<Person> personListNew = personList.stream()
                .filter(Objects::nonNull)
                .map(person -> {
                    Person personNew = new Person(person.getName(), 0, 0, null, null);
                    personNew.setSalary(person.getSalary() + 1000);
                    return personNew;
                }).collect(Collectors.toList());
        System.out.println("一次改动前:" + personList.get(0).getName() + "-->" + personList.get(0).getSalary());
        System.out.println("一次改动后:" + personListNew.get(0).getName() + "-->" + personListNew.get(0).getSalary());

        //方法2:改变原来员工集合的方式(改变了数据源)
        List<Person> personListNew2 = personList.stream()
                .filter(Objects::nonNull)
                .peek(person -> person.setSalary(person.getSalary() + 1000))
                .collect(Collectors.toList());
        System.out.println("二次改动前:" + personList.get(0).getName() + "-->" + personListNew.get(0).getSalary());
        System.out.println("二次改动后:" + personListNew2.get(0).getName() + "-->" + personListNew.get(0).getSalary());
        System.out.println("===================================");

        List<String> collectTemp = Stream.of("one", "two", "three", "four")
                .filter(Objects::nonNull)
                .filter(e -> e.length() > 3)
                .peek(e -> System.out.println("Filtered value: " + e))
                .map(String::toUpperCase)
                .peek(e -> System.out.println("Mapped value: " + e))
                .collect(Collectors.toList());
        System.out.println("peek: " + collectTemp);
        System.out.println("===================================");

        //案例三:将两个字符数组合并成一个新的字符数组。
        List<String> list1 = Arrays.asList("m-k-l-a", "1-3-5-7");
        List<String> list1New = list1.stream()
                .filter(Objects::nonNull)
                .flatMap(s -> Arrays.stream(s.split("-")))
                .collect(Collectors.toList());
        System.out.println("处理前的集合:" + list1);
        System.out.println("处理后的集合:" + list1New);
        System.out.println("===================================");

3.5 Reduce (reduce). map-reduce operation.

Reduction, also called reduction, is to reduce a stream to a value, which can implement operations such as summation, product, and maximum value of a set. Compared with the reduce method provided by the stream itself, the reducing method provided by the Collectors class adds support for custom reduction.

 //案例一:求Integer集合的元素之和、乘积、最大值。
        List<Integer> integerList = Arrays.asList(1, 3, 2, 8, 11, 4);
        //求和方式一
        Optional<Integer> sum1 = integerList.stream()
                .filter(Objects::nonNull)
                .reduce((x, y) -> x + y);
        //求和方式二
        Optional<Integer> sum2 = integerList.stream()
                .filter(Objects::nonNull)
                .reduce(Integer::sum);
        //求和方式三
        Integer sum3 = integerList.stream()
                .filter(Objects::nonNull)
                .reduce(0, Integer::sum);
        System.out.printf("list求和:%d,%d,%d%n", sum1.get(), sum2.get(), sum3);
        //求乘积
        Optional<Integer> product = integerList.stream()
                .filter(Objects::nonNull)
                .reduce((x, y) -> x * y);
        System.out.printf("list求积:%d%n", product.get());
        //求最大值方式1
        Integer max1 = integerList.stream()
                .filter(Objects::nonNull)
                .reduce(1, Integer::max);
        //求最大值方式2
        Optional<Integer> max2 = integerList.stream()
                .filter(Objects::nonNull)
                .reduce((x, y) -> x > y ? x : y);
        System.out.println("list求和:" + max1 + ", " + max2);

        //案例二:求所有员工的工资之和和最高工资。
        //求工资之和方式1:
        Optional<Integer> sumSalary = personList.stream().filter(Objects::nonNull).map(Person::getSalary).reduce(Integer::sum);
        //求工资之和方式2:
        Integer sumSalary2 = personList.stream().filter(Objects::nonNull).reduce(0, (sum, p) -> sum += p.getSalary(), (sum11, sum22) -> sum11 + sum22);
        //求工资之和方式3:
        Integer sumSalary3 = personList.stream().filter(Objects::nonNull).reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);
        System.out.println("工资之和:" + sumSalary.get() + "," + sumSalary2 + "," + sumSalary3);

        //求最高工资方式1:
        Optional<Integer> maxSalary = personList.stream().filter(Objects::nonNull).map(Person::getSalary).reduce(Integer::max);
        Optional<Integer> minSalary = personList.stream().filter(Objects::nonNull).map(Person::getSalary).reduce(Integer::min);
        //求最高工资方式2:
        Integer maxSalary2 = personList.stream().filter(Objects::nonNull).reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), Integer::max);
        //求最高工资方式3:
        Integer maxSalary3 = personList.stream().filter(Objects::nonNull).reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), (max11, max22) -> max11 > max22 ? max11 : max22);
        System.out.println("最高工资:" + maxSalary.get() + "," + minSalary.get() + "," + maxSalary2 + "," + maxSalary3);
        System.out.println("===================================");

3.6 Collect

collect, Collection can be said to be the most versatile and feature-rich part. To understand it literally, it means to collect a stream, and eventually it can be collected into a value, or it can be collected into a new collection.

Collect mainly relies on static methods built into the java.util.stream.Collectors class.

3.6.1 Collection (toList, toSet, toMap)

Because the stream does not store data, after the data in the stream is processed, the data in the stream needs to be recollected into a new collection. toList, toSet, and toMap are more commonly used, and there are more complex usages such as toCollection and toConcurrentMap.

        List<Integer> list3 = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
        List<Integer> listNew = list3.stream()
                .filter(Objects::nonNull)
                .filter(x -> x % 2 == 0)
                .collect(Collectors.toList());
        Set<Integer> listSet = list3.stream()
                .filter(Objects::nonNull)
                .filter(x -> x % 2 == 0)
                .collect(Collectors.toSet());
        HashSet<Integer> listHashSet = list3.stream()
                .filter(Objects::nonNull)
                .filter(x -> x % 2 == 0)
                .collect(Collectors.toCollection(HashSet::new));
        System.out.println("toList: " + listNew + ",toSet: " + listSet + ",listHashSet: " + listHashSet);

        Map<String, Person> personMap = personList.stream()
                .filter(Objects::nonNull)
                .filter(p -> p.getSalary() > 9500)
                .collect(Collectors.toMap(Person::getName, p -> p));
        System.out.println("toMap: " + personMap);
        System.out.println("===================================");

3.6.2 Statistics (count, averaging)

CollectorsProvides a series of static methods for data statistics:

  • count:count

  • averagingIntAverage: averagingLong, ,averagingDouble

  • Most maxByvalue: ,minBy

  • summingIntSummation: summingLong, ,summingDouble

  • All statistical values summarizingIntabove: summarizingLong, ,summarizingDouble

        //案例:统计员工人数、平均工资、工资总额、最高工资。
        List<Person> personDtoList = Arrays.asList(
                new Person("Tom8", 8000, 23, "male", "New York"),
                new Person("Jack7", 7000, 25, "male", "Washington"),
                new Person("Lily7", 7500, 21, "female", "Washington"),
                new Person("Anni9", 9000, 22, "female", "New York"),
                new Person("Owen9", 9000, 21, "male", "New York"),
                new Person("Alisa10", 10000, 21, "female", "New York"),
                null
        );
        //求员工总数
        long countPerson = personDtoList.stream()
                .filter(Objects::nonNull)
                .count();
        //求平均工资
        float averagePerson = personDtoList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.averagingLong(Person::getSalary)).floatValue();
        //求最高工资
        OptionalLong maxPerson = personDtoList.stream()
                .filter(Objects::nonNull)
                .mapToLong(Person::getSalary).max();
        //求工资之和
        long sumPerson = personDtoList.stream()
                .filter(Objects::nonNull)
                .mapToLong(Person::getSalary).sum();
        //一次性统计上述所有信息
        LongSummaryStatistics collect = personDtoList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.summarizingLong(Person::getSalary));
        System.out.println("员工总数:" + countPerson);
        System.out.println("员工平均工资:" + averagePerson);
        System.out.println("员工最高工资:" + maxPerson);
        System.out.println("员工工资总和:" + sumPerson);
        System.out.println("员工工资所有统计:" + collect);
        System.out.println("===================================");

3.6.3 Grouping and partitioning (partitioningBy, groupingBy)

  • Zoning: The streampress is divided into two conditions Map, such as employee salaries is higher than 8000 by divided into two parts.

  • Grouping: Divide the collection into multiple Maps, such as grouping employees by gender. There are single-level grouping and multi-level grouping.

        //将员工按薪资是否高于8000分组
        Map<Boolean, List<Person>> booleanPersonListMap = personDtoList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.partitioningBy(p -> p.getSalary() > 8000));
        System.out.println("员工按薪资是否大于8000分组情况:" + booleanPersonListMap);
        //将员工按性别分组
        Map<String, List<Person>> sexPersonListMap = personDtoList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.groupingBy(Person::getSex));
        System.out.println("员工按性别分组情况:" + sexPersonListMap);
        //将员工先按性别分组,再按地区分组
        Map<String, Map<String, List<Person>>> sexMapAreaPersonListMap = personDtoList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
        System.out.println("员工按性别、地区:" + sexMapAreaPersonListMap);
员工按薪资是否大于8000分组情况:{false=[Person{name='Tom8', salary=8000, age=23, sex='male', area='New York'}, Person{name='Jack7', salary=7000, age=25, sex='male', area='Washington'}, Person{name='Lily7', salary=7500, age=21, sex='female', area='Washington'}], true=[Person{name='Anni9', salary=9000, age=22, sex='female', area='New York'}, Person{name='Owen9', salary=9000, age=21, sex='male', area='New York'}, Person{name='Alisa10', salary=10000, age=21, sex='female', area='New York'}]}

员工按性别分组情况:{female=[Person{name='Lily7', salary=7500, age=21, sex='female', area='Washington'}, Person{name='Anni9', salary=9000, age=22, sex='female', area='New York'}, Person{name='Alisa10', salary=10000, age=21, sex='female', area='New York'}], male=[Person{name='Tom8', salary=8000, age=23, sex='male', area='New York'}, Person{name='Jack7', salary=7000, age=25, sex='male', area='Washington'}, Person{name='Owen9', salary=9000, age=21, sex='male', area='New York'}]}

员工按性别、地区:{female={New York=[Person{name='Anni9', salary=9000, age=22, sex='female', area='New York'}, Person{name='Alisa10', salary=10000, age=21, sex='female', area='New York'}], Washington=[Person{name='Lily7', salary=7500, age=21, sex='female', area='Washington'}]}, male={New York=[Person{name='Tom8', salary=8000, age=23, sex='male', area='New York'}, Person{name='Owen9', salary=9000, age=21, sex='male', area='New York'}], Washington=[Person{name='Jack7', salary=7000, age=25, sex='male', area='Washington'}]}}

3.6.4 Joining

joining The elements in the stream can be concatenated into a string with a specific connector (or directly concatenated if not).

        //将员工的姓名连接成字符串
        String nameStr = personDtoList.stream()
                .filter(Objects::nonNull)
                .map(Person::getName)
                .collect(Collectors.joining());
        //将员工的姓名连接成字符串,用","拼接
        String nameStr2 = personDtoList.stream()
                .filter(Objects::nonNull)
                .map(Person::getName)
                .collect(Collectors.joining(","));
        System.out.println("拼接后的字符串:nameStr=" + nameStr + "。nameStr2=" + nameStr2);
        List<String> strings = Arrays.asList("A", "B", "C");
        String string = strings.stream().collect(Collectors.joining("-"));
        System.out.println("拼接后的字符串:" + string);

        //规约操作
        Integer sumC = personDtoList.stream()
                .filter(Objects::nonNull)
                .map(Person::getSalary)
                .reduce(0, (i, j) -> (i + j - 5000));
        System.out.println("员工扣税薪资总和:" + sumC);
        Optional<Integer> sumC2 = personDtoList.stream()
                .filter(Objects::nonNull)
                .map(Person::getSalary)
                .reduce(Integer::sum);
        System.out.println("员工薪资总和:" + (sumC2.isPresent() ? sumC2.get() : 0));
        System.out.println("===================================");

3.7 sorted

sorted, intermediate operation . There are two sorts:

  • sorted( ): Natural sorting, elements in the stream need to implement the Comparable interface

  • sorted (Comparator com): Comparator sorter custom sorting

        List<Person> personDtoList2 = Arrays.asList(
                new Person("Tom8", 8000, 23, "male", "New York"),
                new Person("Lily7", 7000, 21, "female", "Washington"),
                new Person("Anni9", 9000, 22, "female", "New York"),
                new Person("Owen9", 9000, 21, "male", "New York"),
                new Person("Alisa10", 10000, 21, "female", "New York"),
                null
        );
        //案例:将员工按工资由高到低(工资一样则按年龄由大到小)排序
        //按工资增序排序
        List<String> salaryList = personDtoList2.stream()
                .filter(Objects::nonNull)
                .sorted(Comparator.comparing(Person::getSalary))
                .map(Person::getName)
                .collect(Collectors.toList());
        System.out.println("按工资自然排序:" + salaryList);
        //按工资倒序排序
        List<String> salaryList2 = personDtoList2.stream()
                .filter(Objects::nonNull)
                .sorted(Comparator.comparing(Person::getSalary).reversed())
                .map(Person::getName)
                .collect(Collectors.toList());
        System.out.println("按工资降序排序:" + salaryList2);
        //先按工资自定义倒排再按年龄自定义倒排(从大到小)
        List<String> salaryList4 = personDtoList2.stream()
                .filter(Objects::nonNull)
                .sorted((p1, p2) -> p1.getSalary() == p2.getSalary() ? p2.getAge() - p1.getAge() : p2.getSalary() - p1.getSalary())
                .map(Person::getName)
                .collect(Collectors.toList());
        System.out.println("先按工资自定义倒排再按年龄自定义倒排:" + salaryList4);
        System.out.println("===================================");

3.8 Extraction and combination

Streams can also be merged, deduplicated, restricted, skipped, etc.

  

       String[] arr1 = {"a", "b", "c", "d"};
        String[] arr2 = {"d", "e", "f", "g"};
        List<String> collect1 = Stream.of(arr1, arr2)
                .filter(Objects::nonNull)
                .flatMap(Arrays::stream)
                .collect(Collectors.toList());
        System.out.println("flatMap合并为一个流,其中的元素就是一个个真实的元素:" + collect1);
        Stream<String> stream1 = Stream.of(arr1);
        Stream<String> stream2 = Stream.of(arr2);
        //concat:合并两个流,去重
        List<String> collect2 = Stream.concat(stream1, stream2)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        System.out.println("流合并,不去重:" + collect2);
        //concat:合并两个流,distinct:去重
        List<String> collect3 = Stream.concat(Stream.of(arr1), Stream.of(arr2))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        System.out.println("流合并,去重:" + collect3);
        //limit:限制从流中获得前n个数据
        List<String> collect4 = Stream.concat(Stream.of(arr1), Stream.of(arr2))
                .filter(Objects::nonNull)
                .distinct()
                .limit(3)
                .collect(Collectors.toList());
        System.out.println("limit:" + collect4);
        //skip:跳过前n个数据
        List<String> collect5 = Stream.concat(Stream.of(arr1), Stream.of(arr2))
                .filter(Objects::nonNull)
                .distinct()
                .sorted()
                .skip(3)
                .collect(Collectors.toList());
        System.out.println("skip:" + collect5);

4. Java has built-in 4 core functional interfaces

Reference: https://blog.csdn.net/cmm0401/article/details/109382942

5. Refer to the wiki, thanks

https://blog.csdn.net/mu_wind/article/details/109516995

 

Guess you like

Origin blog.csdn.net/cmm0401/article/details/109655115
Recommended