New feature of Java 8: detailed use of Stream

1, Introduction

   the Java 8 API adds a new abstraction called stream, which allows you to process data in a declarative way, similar to the intuitive way of querying data from the database with SQL statements to provide a high-level abstraction for Java collection operation and expression. The stream API regards the collection of elements to be processed as a stream. The stream is transmitted in the pipeline and can be processed on the nodes of the pipeline, such as search, filtering, sorting, aggregation and so on. Stream API can greatly improve the work efficiency of Java programmers and make the code more concise and clean.

  • Stream itself does not store elements
  • Stream will not change the data source object, but will return a new stream that produces a holding result
  • Steam operations are delayed, which means they wait until the results are needed

2, Common methods of creating streams

2.1 use static methods in Stream: of(), iterate(), generate()

    @Test
    public void stream(){
        //1.1 pass in variable parameters, strings, numbers, etc
        Stream<String> stringStream = Stream.of("Alian", "boy", "cat", "papa");
        //1.2 incoming objects
        Stream<User> userStream = Stream.of(new User("BAT031", "Hu Yifei", "Sales Department", 28, 3500));

        //2.1 the parameter of generate method is the subclass of function < T, t > function interface, such as generating positive odd numbers
        Stream<Integer> oddStream = Stream.iterate(1, (x) -> x + 2);
        oddStream.limit(5).forEach(System.out::println);

        //3.1 the parameter of generate method is supplier < T > supply interface. For example, generate random numbers of 1-1000: (int) math round(Math.random() * (m - n) + n)
        Stream<Integer> generateStream = Stream.generate(() -> (int) Math.round(Math.random() * (1000 - 1) + 1));
        generateStream.limit(10).forEach(System.out::println);//Print 10 random numbers
    }

2.2 use the stream() and parallelStream() methods under Collection

Stream is a sequential stream and parallelStream is a parallel stream.

    @Test
    public void streamAndParallelStream(){
        //Initialize a list
        List<String> fruitList = Arrays.asList("apple","banana","orange","watermelon","pear");
        //Get a sequential stream
        Stream<String> stream = fruitList.stream();
        System.out.println("--------Get the result of sequential flow-----------");
        stream.forEach(System.out::println);
        //Get a parallel stream
        Stream<String> parallel = fruitList.parallelStream();
        System.out.println("--------Get the result of parallel flow-----------");
        parallel.forEach(System.out::println);
    }

Operation results:

--------Get the result of sequential flow-----------
apple
banana
orange
watermelon
pear
--------Get the result of parallel flow-----------
orange
watermelon
banana
apple
pear

2.3 use the stream() method in Arrays to convert the array into a stream

    @Test
    public void arraysToStream(){
        //Initialize a String array (of course, you can also go to other types of arrays)
        String[] animal = new String[]{"cat","dog","pig","chicken","duck"};
        Stream<String> animalStream = Arrays.stream(animal);
        animalStream.forEach(System.out::println);
    }

Operation results:

cat
dog
pig
chicken
duck

2.4 using BufferedReader Lines() method

    @Test
    public void readLineStream() throws FileNotFoundException {
        //Get a stream through BufferedReader (write a file yourself, such as "C:\myStream.txt" here)
        BufferedReader bufReader = new BufferedReader(new FileReader("C:\\myStream.txt"));
        Stream<String> lineStream = bufReader.lines();
        lineStream.forEach(System.out::println);
    }

Operation results:

I'm using Java 8 Stream API Test(BufferedReader.lines()Get stream by)

3, Intermediate operations

3.1 Stateless

3.1.1 filter - filter operation

The   filter method filters the original Stream according to the specified conditions. In the new Stream, only the elements that meet the conditions are included, and the elements that do not meet the conditions are filtered out.

    @Test
    public void filter() {
    	//Initialize a user list
        List<User> userList = Arrays.asList(
                new User("BAT001", "Hu Haotian", "Sales Department", 28, 3500),
                new User("BAT002", "Da Chui Wang", "Sales Department", 27, 3000),
                new User("BAT003", "Tang Erpeng", "R & D department", 32, 9900),
                new User("BAT004", "Wang Yilin", "R & D department", 30, 9000));
        //Filter out employees older than 28 in the user table
        List<User> collect = userList.stream().filter(f -> f.getAge() > 28).collect(Collectors.toList());
        System.out.println("Information of employees over 28 years old:" + collect);
        //Filter out the employees who are older than 28 years old and whose salary is more than 9000 yuan in the user table
        List<User> collect2 = userList.stream().filter(f -> (f.getAge() > 28 && f.getSalary() > 9000)).collect(Collectors.toList());
        System.out.println("Information of employees over 28 years old and with a salary of more than 9000 yuan:" + collect2);
    }

Operation results:

Information of employees over 28 years old:[User(id=BAT003, name=Tang Erpeng, age=32, department=R & D department, salary=9900.0), User(id=BAT004, name=Wang Yilin, age=30, department=R & D department, salary=9000.0)]
Information of employees over 28 years old and with a salary of more than 9000 yuan:[User(id=BAT003, name=Tang Erpeng, age=32, department=R & D department, salary=9900.0)]

3.1.2 map - mapping and conversion operations

   map takes a function as an argument, which is applied to each element and mapped to a new element. The map method will use the given conversion function to convert the elements contained in the Stream. The newly generated Stream only contains the elements generated by the conversion.

    @Test
    public void map() {
        //Initialize a user list
        List<User> userList = Arrays.asList(
                new User("BAT005", "Liang Nansheng", "R & D department", 27, 8000),
                new User("BAT006", "Bao Yaxin", "Finance Department", 25, 6000),
                new User("BAT007", "Luo kaocong", "Testing department", 35, 7400.0));
        //Get the name of the employee in the list (the newly generated Stream only contains the elements generated by the transformation)
        List<String> collect = userList.stream().map(User::getName).collect(Collectors.toList());
        System.out.println("Obtained employee name:" + collect);
        //mapToDouble
        System.out.println("Employees' wages are converted into double: ");
        userList.stream().mapToDouble(User::getSalary).forEach(System.out::println);
        //mapToInt
        System.out.println("The age of employees has changed to int: ");
        userList.stream().mapToInt(User::getAge).forEach(System.out::println);
    }

Operation results:

Obtained employee name:[Liang Nansheng, Bao Yaxin, Luo kaocong]
Employees' wages are converted into double: 
8000.0
6000.0
7400.0
 The age of employees has changed to int: 
27
25
35

3.1.3 flatmap - mapping and conversion operations

   flatmap takes a function as a parameter, converts each value in the Stream into another Stream, and then connects all streams into one Stream. Each value in each partial Stream becomes a separate small Stream, which is then concatenated into a whole Stream. That is, each element in the Stream is converted through the conversion function. The difference is that the object of the conversion function is a Stream, and a new Stream will not be created, but the element of the original Stream will be replaced by the converted Stream

    @Test
    public void flatMap() {
        //The parameter received by flatmap is a Stream
        System.out.println("1, The output result after replacing the short horizontal line in the flow:");
        Stream.of("A-l-i-a-n ","l-o-v-e ","C-S-D-N").flatMap(e->Stream.of(e.split("-"))).forEach(System.out::print);
        System.out.println();
        System.out.println("2, Multiply each data in the stream by 10:");
        Stream.of(2,5,8,9).flatMap(n->Stream.of(n*10)).forEach(System.out::println);
    }

Operation results:

1, The output result after replacing the short horizontal line in the flow:
Alian love CSDN
 2, Multiply each data in the stream by 10:
20
50
80
90

3.1.4 peek - pick out operation

   peek method can get every element in the Stream like map, but map receives a Function expression with a return value; Peek receives a Consumer expression without a return value. Peek method will generate a new Stream containing all elements of the original Stream and provide a consumption Function (Consumer instance). When each element of the new Stream is consumed, the given consumption Function will be executed, and the consumption Function will be executed first.

    @Test
    public void peek() {
        //Initialize a user list
        List<User> userList = Arrays.asList(
                new User("BAT008", "Zhang Weijie", "Testing department", 24, 7000),
                new User("BAT009", "Hu Junwei", "R & D department", 24, 4500));
        List<User> collect = userList.stream().peek(p -> p.setDepartment("Operation and maintenance department")).collect(Collectors.toList());
        System.out.println("All departments are changed to operation and maintenance department:"+collect);
    }

Operation results:

Information after all departments are changed to operation and maintenance department:[User(id=BAT008, name=Zhang Weijie, age=24, department=Operation and maintenance department, salary=7000.0), User(id=BAT009, name=Hu Junwei, age=24, department=Operation and maintenance department, salary=4500.0)]

3.2 Stateful

3.2.1 distinct - de duplication operation

   the distinct method eliminates the duplicate elements in the original Stream, and there are no duplicate elements in the generated new Stream.

    @Test
    public void distinct() {
        System.out.println("De duplication results by type:");
        Stream.of(3, 6, 9, 3, 9, 5).distinct().forEach(System.out::println);
        List<User> userList = Arrays.asList(
            new User("BAT010", "Hu Jianer", "Ministry of Personnel", 23, 4000),
            new User("BAT010", "Hu Jianer", "Ministry of Personnel", 23, 4000),
            new User("BAT011", "Tao Jianwen", "Operation and maintenance department", 25, 8000));
        System.out.println("De duplication result by object:");
        userList.stream().distinct().forEach(System.out::println);
    }

Operation results:

De duplication results by type:
3
6
9
5
 De duplication result by object:
User(id=BAT010, name=Hu Jianer, age=23, department=Ministry of Personnel, salary=4000.0)
User(id=BAT011, name=Tao Jianwen, age=25, department=Operation and maintenance department, salary=8000.0)

3.2.2 sorted - natural sort

The sorted method will sort the original Stream and return an ordered new Stream.

    @Test
    public void sorted() {
        //Natural sorting results
        System.out.println("Natural sorting results of numbers:");
        Stream.of(15, 28, 6, 9).sorted().forEach(System.out::println);
        System.out.println("Natural sorting result of characters:");
        Stream.of("b", "ab", "ba", "c").sorted().forEach(System.out::println);
    }

Operation results:

Natural sorting results of numbers:
6
9
15
28
 Natural sorting result of characters:
ab
b
ba
c

3.2.3 sorted(Comparator com) - specify sorting

The sorted(Comparator) method receives a custom collation function (Comparator).

    @Test
    public void sortedWithCompare() {
        List<User> userList = Arrays.asList(
                new User("BAT010", "Hu Jianer", "Ministry of Personnel", 23, 4000),
                new User("BAT011", "Tao Jianwen", "Operation and maintenance department", 25, 8000),
                new User("BAT012", "Zhang Mengmeng", "Administration Department", 20, 3500));
        //Sort by age in ascending order
        System.out.println("Sort by age in ascending order");
        userList.stream().sorted(Comparator.comparingInt(User::getAge)).forEach(System.out::println);
        //Sort by age in reverse order
        System.out.println("Sort by age in reverse order");
        userList.stream().sorted(Comparator.comparingInt(User::getAge).reversed()).forEach(System.out::println);
    }

Operation results:

Sort by age in ascending order
User(id=BAT012, name=Zhang Mengmeng, age=20, department=Administration Department, salary=3500.0)
User(id=BAT010, name=Hu Jianer, age=23, department=Ministry of Personnel, salary=4000.0)
User(id=BAT011, name=Tao Jianwen, age=25, department=Operation and maintenance department, salary=8000.0)
Sort by age in reverse order
User(id=BAT011, name=Tao Jianwen, age=25, department=Operation and maintenance department, salary=8000.0)
User(id=BAT010, name=Hu Jianer, age=23, department=Ministry of Personnel, salary=4000.0)
User(id=BAT012, name=Zhang Mengmeng, age=20, department=Administration Department, salary=3500.0)

3.2.4 limit - current limiting operation

The limit(n) method limits the first n data obtained from the stream.

    @Test
    public void limit() {
        List<User> userList = Arrays.asList(
                new User("BAT010", "Hu Jianer", "Ministry of Personnel", 23, 4000),
                new User("BAT011", "Tao Jianwen", "Operation and maintenance department", 25, 8000),
                new User("BAT012", "Zhang Mengmeng", "Administration Department", 20, 3500));
        //Take the first two records after sorting in reverse order by age
        System.out.println("Take the first two records after sorting in reverse order by age:");
        userList.stream().sorted(Comparator.comparingInt(User::getAge).reversed()).limit(2).forEach(System.out::println);
    }

Operation results:

Take the first two records after sorting in reverse order by age:
User(id=BAT011, name=Tao Jianwen, age=25, department=Operation and maintenance department, salary=8000.0)
User(id=BAT010, name=Hu Jianer, age=23, department=Ministry of Personnel, salary=4000.0)

3.2.5 skip - skip operation

The skip(n) method skips n elements and can operate with limit.

    @Test
    public void skip() {
        List<User> userList = Arrays.asList(
                new User("BAT010", "Hu Jianer", "Ministry of Personnel", 23, 4000),
                new User("BAT011", "Tao Jianwen", "Operation and maintenance department", 25, 8000),
                new User("BAT012", "Zhang Mengmeng", "Administration Department", 20, 3500));
        //Take the first two records after sorting in reverse order by age
        System.out.println("Skip one piece of data and take two records after sorting in reverse order according to age:");
        userList.stream().sorted(Comparator.comparingInt(User::getAge).reversed()).skip(1).limit(2).forEach(System.out::println);
    }

Operation results:

Skip one piece of data and take two records after sorting in reverse order according to age:
User(id=BAT010, name=Hu Jianer, age=23, department=Ministry of Personnel, salary=4000.0)
User(id=BAT012, name=Zhang Mengmeng, age=20, department=Administration Department, salary=3500.0)

4, Terminal operations

4.1 non short circuit operation

4.1.1 forEach - traversal operation

The forEach method has been used many times before. It is used to traverse the elements in the Stream. The sequential Stream is output in the order of inserting data, and the parallel Stream is output randomly.

    @Test
    public void forEach() {
        //Initialize a data list
        List<Integer> list = Arrays.asList(2, 3, 4, 5, 6);
        System.out.println("Sequential downstream output:");
        list.stream().sorted().forEach(f -> System.out.println("forEach Sequential streaming data:" + f));
        System.out.println("Parallel streaming output:");
        list.parallelStream().forEach(f -> System.out.println("forEach Parallel streaming data:" + f));
        List<User> userList = Arrays.asList(
                new User("BAT010", "Hu Jianer", "Ministry of Personnel", 23, 4000),
                new User("BAT011", "Tao Jianwen", "Operation and maintenance department", 25, 8000),
                new User("BAT012", "Zhang Mengmeng", "Administration Department", 20, 3500));
        //Take the first two records after sorting in reverse order by age
        System.out.println("Output after skipping the previous data:");
        userList.stream().skip(1).forEach(System.out::println);
    }

Operation results:

Sequential downstream output:
forEach Sequential streaming data: 2
forEach Sequential streaming data: 3
forEach Sequential streaming data: 4
forEach Sequential streaming data: 5
forEach Sequential streaming data: 6
 Parallel streaming output:
forEach Parallel streaming data: 4
forEach Parallel streaming data: 6
forEach Parallel streaming data: 5
forEach Parallel streaming data: 2
forEach Parallel streaming data: 3
 Output after skipping the previous data:
User(id=BAT011, name=Tao Jianwen, age=25, department=Operation and maintenance department, salary=8000.0)
User(id=BAT012, name=Zhang Mengmeng, age=20, department=Administration Department, salary=3500.0)

4.1.2 forEachOrdered - traversal operation

The forEachOrdered method is similar to forEach in that it traverses all elements in a Stream. The difference is that if the Stream has a preset order, it will be executed in the preset order (the Stream is unordered). The default is the order in which elements are inserted. In the sequential Stream, the data is output in the order of inserting data, and the encounter order of the Stream is maintained in the parallel Stream.

    @Test
    public void forEachOrdered() {
        List<Integer> list = Arrays.asList(2, 3, 4, 5, 6, 7);
        System.out.println("forEachOrdered Sequential downstream output:");
        list.parallelStream().forEachOrdered(f -> System.out.println("forEachOrdered Sequential streaming data:" + f));
        System.out.println();
        System.out.println("forEachOrdered Parallel streaming output(The order in which the stream is encountered is maintained): ");
        list.parallelStream().forEachOrdered(f -> System.out.println("forEachOrdered Parallel streaming data:" + f));
    }

Operation results:

forEachOrdered Sequential downstream output:
forEachOrdered Sequential streaming data: 2
forEachOrdered Sequential streaming data: 3
forEachOrdered Sequential streaming data: 4
forEachOrdered Sequential streaming data: 5
forEachOrdered Sequential streaming data: 6
forEachOrdered Sequential streaming data: 7

forEachOrdered Parallel streaming output(The order in which the stream is encountered is maintained): 
forEachOrdered Parallel streaming data: 2
forEachOrdered Parallel streaming data: 3
forEachOrdered Parallel streaming data: 4
forEachOrdered Parallel streaming data: 5
forEachOrdered Parallel streaming data: 6
forEachOrdered Parallel streaming data: 7

4.1.3 toArray - array operation

toArray can be converted into an array, or a custom array generator can be provided

    @Test
    public void toArray() {
        Object[] animal= Stream.of("cat", "dog", "pig", "chicken", "duck").toArray();
        for(Object a:animal){
            System.out.println("The array contains:"+a);
        }
    }

Operation results:

The array contains: cat
 The array contains: dog
 The array contains: pig
 The array contains: chicken
 The array contains: duck

4.1.4 reduce - protocol operation

The reduce method is a specification operation, and all elements are reduced to one. For example, sum and product all elements. Here we implement a method of summation and product, and specify the initialization values as 0 and 1 respectively (multiplication starts with 1, otherwise it doesn't make sense)

    @Test
    public void reduce() {
        int sum = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).reduce(0, Integer::sum);
        System.out.println("1 The sum of to 10 is equal to:" + sum);
        int product = Stream.of(1, 2, 3, 4, 5).reduce(1, (e1, e2) -> e1 * e2);
        System.out.println("1 The product of to 5 equals:" + product);
    }

Operation results:

1 The sum of to 10 equals 55
1 The product of to 5 equals 120

4.1.5 collect - collection operation

We have also used the collect operation many times, but there is no more detail

@Test
    public void collect() {
        //Initialize a user list
        List<User> userList = Arrays.asList(
                new User("BAT004", "Wang Yilin", "R & D department", 30, 9000),
                new User("BAT005", "Liang Nansheng", "R & D department", 27, 8000),
                new User("BAT006", "Bao Yaxin", "Finance Department", 25, 6000),
                new User("BAT007", "Luo kaocong", "Testing department", 35, 7400.0));
        //Sort by age and turn to list
        System.out.println("----------turn list Results after----------");
        userList.stream().sorted(Comparator.comparingInt(User::getAge)).collect(Collectors.toList()).forEach(System.out::println);
        //Sort by salary and convert to set
        System.out.println("----------turn set Results after----------");
        userList.stream().sorted(Comparator.comparingDouble(User::getSalary)).collect(Collectors.toCollection(LinkedHashSet::new)).forEach(System.out::println);
        //Take the employee number as the key and the employee information as the value to be converted into map
        System.out.println("----------Take the employee's number as the reference key,Employee information as value Convert to map----------");
        Map<String, User> collect = userList.stream().collect(Collectors.toMap(User::getId, u -> u));
        collect.forEach((x, y) -> System.out.println(x + "->" + y));
        //Separate names with commas
        System.out.println("----------Name stitching results----------");
        String nameStr = userList.stream().map(User::getName).collect(Collectors.joining(","));
        System.out.println(nameStr);
        System.out.println("----------Statistics by Department----------");
        //Count the number of people by department
        Map<String, Long> groupingBy = userList.stream().collect(Collectors.groupingBy(User::getDepartment, Collectors.counting()));
        groupingBy.forEach((x, y) -> System.out.println(x + "->" + y));
        //Get salary summary information
        System.out.println("----------Salary summary information----------");
        DoubleSummaryStatistics statistics = userList.stream().collect(Collectors.summarizingDouble(User::getSalary));
        System.out.println("Maximum wage:" + statistics.getMax());
        System.out.println("Minimum wage:" + statistics.getMin());
        System.out.println("Total wages:" + statistics.getSum());
        System.out.println("Draw salary:" + statistics.getAverage());
        System.out.println("Total records:" + statistics.getCount());
    }

Operation results:

----------turn list Results after----------
User(id=BAT006, name=Bao Yaxin, age=25, department=Finance Department, salary=6000.0)
User(id=BAT005, name=Liang Nansheng, age=27, department=R & D department, salary=8000.0)
User(id=BAT004, name=Wang Yilin, age=30, department=R & D department, salary=9000.0)
User(id=BAT007, name=Luo kaocong, age=35, department=Testing department, salary=7400.0)
----------turn set Results after----------
User(id=BAT006, name=Bao Yaxin, age=25, department=Finance Department, salary=6000.0)
User(id=BAT007, name=Luo kaocong, age=35, department=Testing department, salary=7400.0)
User(id=BAT005, name=Liang Nansheng, age=27, department=R & D department, salary=8000.0)
User(id=BAT004, name=Wang Yilin, age=30, department=R & D department, salary=9000.0)
----------Take the employee's number as the reference key,Employee information as value Convert to map----------
BAT004->User(id=BAT004, name=Wang Yilin, age=30, department=R & D department, salary=9000.0)
BAT007->User(id=BAT007, name=Luo kaocong, age=35, department=Testing department, salary=7400.0)
BAT005->User(id=BAT005, name=Liang Nansheng, age=27, department=R & D department, salary=8000.0)
BAT006->User(id=BAT006, name=Bao Yaxin, age=25, department=Finance Department, salary=6000.0)
----------Name stitching results----------
Wang Yilin,Liang Nansheng,Bao Yaxin,Luo kaocong
----------Statistics by Department----------
Testing department->1
 Finance Department->1
 R & D department->2
----------Salary summary information----------
Maximum wage: 9000.0
 Minimum wage: 6000.0
 Total salary: 30400.0
 Draw salary: 7600.0
 Total records: 4

4.1.6 max - maximum operation

The max method returns an option according to the specified Comparator. The value in the option is the largest element in the Stream.

    @Test
    public void max() {
        //Initialize a user list
        List<User> userList = Arrays.asList(
                new User("BAT005", "Liang Nansheng", "R & D department", 27, 8000),
                new User("BAT006", "Bao Yaxin", "Finance Department", 25, 6000),
                new User("BAT007", "Luo kaocong", "Testing department", 35, 7400.0));
        //Filter out the information of the oldest employee
        Optional<User> userOptional = userList.stream().max(Comparator.comparingInt(User::getAge));
        //It's just a demonstration. There's no judgment here
        User user = userOptional.get();
        System.out.println("Information of the oldest employee:" + user);
    }

Operation results:

Information of the oldest employee: User(id=BAT007, name=Luo kaocong, age=35, department=Testing department, salary=7400.0)

4.1.7 min - minimum operation

The min method returns an option according to the specified Comparator. The value in the option is the smallest element in the Stream.

    @Test
    public void min() {
        //Initialize a user list
        List<User> userList = Arrays.asList(
                new User("BAT005", "Liang Nansheng", "R & D department", 27, 8000),
                new User("BAT006", "Bao Yaxin", "Finance Department", 25, 6000),
                new User("BAT007", "Luo kaocong", "Testing department", 35, 7400.0));
        //Filter out the information of the lowest paid employees
        Optional<User> userOptional = userList.stream().min(Comparator.comparingDouble(User::getSalary));
        //It's just a demonstration. There's no judgment here
        User user = userOptional.get();
        System.out.println("Minimum wage employee information:" + user);
    }

Operation results:

Minimum wage employee information: User(id=BAT006, name=Bao Yaxin, age=25, department=Finance Department, salary=6000.0)

4.1.8 count - Statistics operation

The count method will return the number of elements in the Stream, which is generally used for statistics after intermediate operations in the Stream.

    @Test
    public void count() {
        //Initialize a user list
        List<User> userList = Arrays.asList(
                new User("BAT005", "Liang Nansheng", "R & D department", 27, 8000),
                new User("BAT006", "Bao Yaxin", "Finance Department", 25, 6000),
                new User("BAT007", "Luo kaocong", "Testing department", 35, 7400.0));
        //Count the number of employees younger than 30
        long count = userList.stream().filter(f -> f.getAge() < 30).count();
        System.out.println("Number of employees younger than 30:" + count);
    }

Operation results:

Number of employees younger than 30: 2	

4.2 short circuiting

4.2.1 anyMatch - match operation (any match)

The anyMatch method returns true if it matches any element in the Stream according to the specified conditions, otherwise it returns false.

    @Test
    public void anyMatch() {
        List<User> userList = Arrays.asList(
                new User("BAT005", "Liang Nansheng", "R & D department", 27, 8000),
                new User("BAT006", "Bao Sanya", "Finance Department", 25, 6000),
                new User("BAT007", "Luo kaocong", "Testing department", 35, 7400),
                new User("BAT008", "Zhang Weijie", "Testing department", 24, 7000));
        //Match any employee older than 35
        boolean b = userList.stream().anyMatch(p -> p.getAge() > 35);
        System.out.println("Match any employee older than 34:" + b);
        //Match any employee with surname "Zhang"
        boolean flag = userList.stream().anyMatch(p -> p.getName().startsWith("Zhang"));
        System.out.println("Employees matching any "Zhang" surname:" + flag);
    }

Operation results:

Match any employee older than 34: false
 Employees matching any "Zhang" surname: true

4.2.2 allMatch - match operation (all match)

The allMatch method returns true only when it matches all the elements in the Stream according to the specified conditions. Otherwise, it returns false.

    @Test
    public void allMatch() {
        List<User> userList = Arrays.asList(
                new User("BAT009", "Hu Junwei", "R & D department", 24, 4500),
                new User("BAT010", "Hu Jianer", "Ministry of Personnel", 23, 4000),
                new User("BAT011", "Tao Jianwen", "Operation and maintenance department", 25, 8000),
                new User("BAT012", "Zhang Mengmeng", "Administration Department", 20, 3500));
        //All matched people were older than 22 years old
        boolean b = userList.stream().allMatch(p -> p.getAge() > 22);
        System.out.println("All are over 22 years old:" + b);
        //All matched people were older than 18 years old
        boolean flag = userList.stream().allMatch(p -> p.getAge() > 18);
        System.out.println("All are older than 18:" + flag);
    }

Operation results:

All are over 22 years old: false
 All are older than 18: true

4.2.3 noneMatch - match operation (no match)

The noneMatch method returns true only if none of the elements in the Stream matches according to the specified conditions. Otherwise, it returns false.

    @Test
    public void noneMatch() {
        List<User> userList = Arrays.asList(
                new User("BAT001", "Hu Haotian", "Sales Department", 28, 3500),
                new User("BAT002", "Da Chui Wang", "Sales Department", 27, 3000),
                new User("BAT003", "Tang Erpeng", "R & D department", 32, 9900),
                new User("BAT004", "Wang Yilin", "R & D department", 30, 9000),
                new User("BAT005", "Liang Nansheng", "R & D department", 27, 8000));
        //There is no employee surnamed "Li" in the match
        boolean b = userList.stream().noneMatch(p -> p.getName().startsWith("Lee"));
        System.out.println("No employee surnamed Li:" + b);
        //There is no employee surnamed "Hu" in the match
        boolean flag = userList.stream().noneMatch(p -> p.getName().startsWith("Hu"));
        System.out.println("No employee surnamed Hu:" + flag);
    }

Operation results:

No employee surnamed Li: true
 No employee surnamed Hu: false

4.2.4 findFirst - find operation (find the first)

The findFirst method is used to obtain the option of the first element in the Stream. If the Stream is empty, an empty option is returned.

    @Test
    public void findFirst() {
        List<User> userList = Arrays.asList(
                new User("BAT003", "Tang Erpeng", "R & D department", 32, 9900),
                new User("BAT004", "Wang Yilin", "R & D department", 30, 9000),
                new User("BAT005", "Liang Nansheng", "R & D department", 27, 8000),
                new User("BAT006", "Bao Yaxin", "Finance Department", 25, 6000)
        );
        Optional<User> first = userList.stream().findFirst();
        System.out.println("First employee found:" + first.get());
    }

Operation results:

First employee found: User(id=BAT003, name=Tang Erpeng, age=32, department=R & D department, salary=9900.0)

4.2.5 findAny - find operation (find any one)

The findAny method is used to obtain the option of an element in the Stream. If the Stream is empty, an empty option is returned, and the first element is always returned in the sequential Stream.

    @Test
    public void findAny() {
        List<User> userList = Arrays.asList(
                new User("BAT006", "Bao Yaxin", "Finance Department", 25, 6000),
                new User("BAT003", "Tang Erpeng", "R & D department", 32, 9900),
                new User("BAT004", "Wang Yilin", "R & D department", 30, 9000),
                new User("BAT005", "Liang Nansheng", "R & D department", 27, 8000)
        );
        Optional<User> userOptional = userList.stream().filter(p->p.getAge()<30).findAny();
        userOptional.ifPresent(user -> System.out.println("Any employee information found:" + user));
    }

Operation results:

Any employee information found: User(id=BAT006, name=Bao Yaxin, age=25, department=Finance Department, salary=6000.0)

epilogue

   the above is what we want to talk about today. It mainly introduces the use of some common methods in Stream. Usually, we still need to look at the API more and strengthen practice to be proficient, which is very helpful for us to continue writing code later.

Keywords: Java Big Data stream

Added by Imperialoutpost on Mon, 31 Jan 2022 08:20:35 +0200