Java8-Stream learning record

  • What is Stream?
    Stream is a queue of elements from a data source and supports aggregation operations (see description below)

  • Aggregation operations are similar to SQL statements, such as filter, map, reduce, find, match, sorted, etc.

There are two basic concepts to understand when using Stream

  1. Pipelining: All intermediate operations return the stream object itself. In this way, multiple operations can be cascaded into a pipeline, just like a fluent style. Doing so can optimize operations, such as laziness and short-circuiting.
  2. Internal iteration: In the past, traversal of the collection was done through Iterator or For-Each, and iterated explicitly outside the collection. This is called external iteration. Stream provides an internal iterative method, implemented through the visitor model (Visitor).

Code practice

  • Ways to Create Streams
    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 (using multi-threaded processing).

  • The following code creates a stream

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

The meaning of the above code is to filter out the empty strings in strings and return a set that does not contain empty strings.
In the code above. The stream is to create a serial stream, and the filter function literally means to filter, but when filtering out, the parameter needs to be passed a functional interface— Predicate. The Predicate interface actually implements its test method when it is used. The return value of this method is true for no filtering, and false for filtering. The above code is rewritten with an anonymous inner class to look like the following:

        List<String> filtered = strings.stream().filter(new Predicate<String>() {
    
    
            @Override
            public boolean test(String string) {
    
    
                return !string.isEmpty();
            }
        }).collect(Collectors.toList());

Using lambda code is more concise, but suddenly it may not know what is in the filter~~, in this way, it is actually an anonymous inner class.
The collect function performs aggregation operations and outputs the results. What needs to be passed is a Collector, and Collections.toList() returns a Collector.

After creating the stream, use forEach to iterate the elements

        Random random=new Random();
        random.ints().limit(5).forEach(System.out::println);
        // 也可以写成下面的形式,更清晰,但是上面的形式更简洁
        random.ints().limit(5).forEach(new IntConsumer() {
    
    
            @Override
            public void accept(int value) {
    
    
                System.out.println(value);
            }
        });

The above code creates a stream, uses forEach to traverse the stream, and prints each element. What is passed in forEach is an IntConsumer interface. After viewing the implementation of this interface, the description of this interface is as follows:

Represents an operation that accepts a single {
    
    @code int}-valued argument and
returns no result

The interface is to receive an integer, and then perform the corresponding operation on the incoming integer, at the same time, the operation has no return value.

map() performs the corresponding operation on each element and returns

The following code finds the square number of each element, and uses distinct() for deduplication. What we pass in the map is a functional interface Function

        List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
        List<Integer> squaresList=numbers.stream().map( x->x*x).distinct().collect(Collectors.toList());
        System.out.println(squaresList);

filter() to filter elements

The following code counts the number of empty strings

        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
        System.out.println(strings.stream().filter(String::isEmpty).count());

Convert int array to collection

		List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());

Convert int array to string

int[] arr = {
    
    1,2,3,4};		
		String str1 = Arrays.stream(arr).boxed().map(i -> i.toString()) //必须将普通数组 boxed才能 在 map 里面 toString
				.collect(Collectors.joining(""));
// 结果为:1234

Guess you like

Origin blog.csdn.net/liu_12345_liu/article/details/104034341