Stream usage in Java

Posted by danielle on Tue, 04 Jan 2022 22:56:31 +0100

Stream usage in Java

preface

Tip: for learning the use of stream stream in java

1, Introduction to steam flow

Java 8 API Added a new abstraction called flow Stream,Allows you to process data in a declarative manner. Stream Use a similar SQL Statement provides an intuitive way to query data from the database Java Higher order abstraction of set operation and expression.
Stream API Can greatly improve Java Programmer productivity, let programmers write efficient, clean and concise code.
This style regards the set of elements to be processed as a stream, which is transmitted in the pipeline and can be processed on the nodes of the pipeline, such as filtering, sorting, aggregation, etc.
Element flows through intermediate operations in the pipeline( intermediate operation)Finally, the final operation(terminal operation)Get the results of the previous processing.

In short, it is simple and efficient. The stream used to manipulate the collection.

What is Stream?

A Stream is a queue of elements from a data source and supports aggregation operations

  • Elements are specific types of objects that form a queue. Stream in Java does not store elements, but calculates on demand.
  • The source of the data stream. It can be set, array, I/O channel, generator, etc.
  • Aggregation operations are similar to SQL statements, such as filter, map, reduce, find, match, sorted, etc.

Unlike previous Collection operations, Stream operations have two basic features:

  • Pipelining: all intermediate operations will return the stream object itself. In this way, multiple operations can be connected in series into a pipe, just like the flow style. Doing so optimizes operations such as laziness and short circuiting.
  • Internal iteration: previously, the collection was traversed through Iterator or for each to explicitly iterate outside the collection, which is called external iteration. Stream provides a way of internal iteration, which is implemented through visitor mode.

Generate flow

In Java 8, the collection interface has two methods to generate streams:

  • stream() − creates a serial stream for the collection.
  • parallelStream() − creates a parallel stream for the collection.

2, Stream stream usage

1.stream simple type sorting

The code is as follows (example):
The code is as follows (example):

        //The limit method of stream stream is used to obtain a specified number of streams
        List<Integer> list = Arrays.asList(12, 5, 4, 27, 25, 6, 18);
        //Positive sequence: mode 1
        list.stream().sorted().forEach(i-> System.out.println(i));
        //Positive sequence: mode 2
        list.stream().sorted(Comparator.comparing(Integer::intValue)).forEach(i-> System.out.println(i));
        //Reverse order: mode 1
        list.stream().sorted(Comparator.comparing(Integer::intValue).reversed()).forEach(i-> System.out.println(i));
        //Do not use expressions
        list.stream().sorted(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });

2.Stream streams are sorted according to a value of the collection object

The code is as follows (example):

        //Sort by a value of a collection object
        //Book object, attribute int bookId;String name;
        Book book1=new Book(5,"Novel 1");
        Book book2=new Book(2,"Novel 2");
        Book book3=new Book(7,"Novel 3");
        List<Book> books = Arrays.asList(book1, book2, book3);
        books.stream().sorted(Comparator.comparing(Book::getBookId)).forEach(book -> System.out.println(book));

3.stream collects a property of a collection object

The code is as follows (example):

        //Collect a property of a collection object
        //Book object, attribute int bookId;String name;
        Book book1=new Book(5,"Novel 1");
        Book book2=new Book(2,"Novel 2");
        Book book3=new Book(7,"Novel 3");
        Book book4=new Book("Novel 4");
        Book book5=new Book("Novel 5");
        List<Book> books = Arrays.asList(book1, book2, book3,book4,book5);
        books.stream().map(Book::getBookId).distinct().filter(x->x!=0).forEach(x-> System.out.println(x));

4. Filter according to an attribute of the object of the collection

The code is as follows (example):

        //Filter based on a property of an object in the collection
        //Book object, attribute int bookId;String name;
        Book book1=new Book(5,"Novel 1");
        Book book2=new Book(2,"Novel 2");
        Book book3=new Book(7,"Novel 3");
        Book book4=new Book(7,"Novel 3");
        Book book5=new Book("Novel 4");
        Book book6=new Book("Novel 5");
        List<Book> books = Arrays.asList(book1, book2, book3,book4,book5);
        books.stream().filter(book -> !(book.bookId==0)).forEach(book -> System.out.println(book));

5. Take the intersection and difference set of two lists

The code is as follows (example):

   //The distinct method of stream stream is used to remove the same data set
        List<Integer> list1 = Arrays.asList(12,5, 5, 4, 27, 25, 26, 18);
        List<Integer> list2= Arrays.asList(10,15, 15, 24, 127, 215, 26, 8);
        // intersection
        List<Integer> intersection = list1.stream().filter(i -> list2.contains(i)).collect(Collectors.toList());
        System.out.println("Intersection: " + intersection);
        // Console output intersection: [26]

        // Difference set (list1-list2)
        List<Integer> reduce1  = list1.stream().filter(integer -> !list2.contains(integer)).collect(Collectors.toList());
        System.out.println("Difference set: " + reduce1);
        // Console output difference set: [12, 5, 5, 4, 27, 25, 18]

        // Union
        List<Integer> listAll1 = list1.parallelStream().collect(Collectors.toList());
        List<Integer> listAll2 = list2.parallelStream().collect(Collectors.toList());
        listAll1.addAll(listAll2);
        System.out.println("Union = " + listAll1);
        // Console output union 1 = [12, 5, 5, 4, 27, 25, 26, 18, 10, 15, 15, 24, 127, 215, 26, 8]

        //De duplication Union
        List<Integer> listAll3 = list1.parallelStream().distinct().collect(Collectors.toList());
        List<Integer> listAll4 = list2.parallelStream().distinct().collect(Collectors.toList());
        listAll4.addAll(listAll2);
        System.out.println("De duplication Union = " + listAll4);
        // Console output de duplication union = [10, 15, 24, 127, 215, 26, 8, 10, 15, 15, 24, 127, 215, 26, 8]

6.stream circulation output

The code is as follows (example):

        Stream Provides a new method 'forEach' To iterate over each data in the flow.
        //Loop of stream
        List<Integer> list = Arrays.asList(12, 5, 4, 27, 25, 6, 18);
        list.stream().forEach(integer -> System.out.println(integer));

7. The stream stream uses the map method to map the corresponding results of each element

The code is as follows (example):

        //In the loop of stream stream, the map method is used to map the corresponding results of each element
         List<Integer> list = Arrays.asList(12, 5, 4, 27, 25, 6, 18);
         List<Integer> collect = list.stream().map(i -> i * i).collect(Collectors.toList());
         collect.stream().forEach(integer -> System.out.println(integer));

8.stream stream uses the limit method to obtain a specified number of streams

The code is as follows (example):

        //The limit method of stream stream is used to obtain a specified number of streams
         List<Integer> list = Arrays.asList(12, 5, 4, 27, 25, 6, 18);
         list.stream().limit(3).forEach(i-> System.out.println(i));

9. Convert stream stream into collection and aggregation elements

The code is as follows (example):

//The stream is converted to collection and aggregation elements. Collectors can be used to return lists or strings:
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
        List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
        System.out.println("Filter list: " + filtered);
        String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining("-"));
        System.out.println("Merge string: " + mergedString);
        /*
		Filter list: [abc, bc, efg, abcd, jkl]
		Merge string: ABC BC EFG ABCD JKL
		*/

10. The distinct method of stream stream is used to remove the same data set

The code is as follows (example):

		//The distinct method of stream stream is used to remove the same data set
        List<Integer> list = Arrays.asList(12,5, 5, 4, 27, 25, 6, 18);
        list.stream().distinct().forEach(x-> System.out.println(x));

summary

Here is a summary of the article:
The above is what we need to remember today. This article only briefly introduces the use of stream. If there are new and interesting ones, we can share them together.

Topics: Java