Detailed explanation of Java8 Stream and examples of using stream creation methods (2)

        This chapter introduces the operation of Stream creation: creating a stream refers to the process of converting a collection or other data source into a Stream object. Normally, we can use the static methods of the Stream class to create stream objects, such as Stream.of(), Collections.stream(), and so on. These methods return a Stream object that can be used to perform various operations on the data. Below are some common ways to create streams. Java8 Stream detailed explanation and intermediate operation creation method use example (1)

  1. of(T... values): Creates a stream consisting of the specified elements.
  2. empty(): Create an empty stream.
  3. generate(Supplier<T> s): Create an infinite stream, each call to the get() method will generate new data.
  4. iterate(T seed, UnaryOperator<T> f): Creates an infinite stream that applies the specified function on each iteration.
  5. concat(Stream<? extends T> a, Stream<? extends T> b): Creates a sequential stream containing two streams, first stream a and then stream b.
  6. builder(): Create a Builder object for building chain operations.
  7. ofNullable(T t): Creates a stream containing zero or one element, the element is the specified object (can be null).
  8. range(int startInclusive, int endExclusive): Creates a sequence stream of integers starting at startInclusive (inclusive) and ending at endExclusive (exclusive).
  9. rangeClosed(int startInclusive, int endInclusive): Creates a sequence stream of integers starting at startInclusive (inclusive) and ending at endInclusive (inclusive).

Detailed introduction to Stream's method of creating a stream

of(T... values)

The of(T... values) method of Stream is a static method used to create a sequential Stream object containing the specified elements.

The specific usage is as follows:

  1. Call the of(T... values) method and pass in one or more elements.
  2. This method will return a Stream object containing the specified elements.

For example, the following code demonstrates how to use the of() method to create a Stream object containing multiple elements:

Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);

The above code will create a Stream object containing the integers 1 to 5. You can use this stream for subsequent operations as needed, such as filtering, mapping, sorting, and so on.

of(T t)

The of(T t) method of Stream is a static method used to create a sequential Stream object containing a single element.

The specific usage is as follows:

  1. Call the of(T t) method and pass in an element.
  2. This method will return a Stream object containing the specified elements.

For example, the following code demonstrates how to use the of() method to create a Stream object containing a single element:

Stream<String> stream = Stream.of("Hello");

The above code will create a Stream object containing the string "Hello". You can use this stream for subsequent operations as needed, such as filtering, mapping, sorting, and so on.

 empty()

empty()method is used to create an empty stream that contains no elements.

Here is an example of usage:

import java.util.stream.Stream;

public class StreamEmptyExample {
    public static void main(String[] args) {
        Stream<String> emptyStream = Stream.empty();
        System.out.println("Count: " + emptyStream.count()); // 输出 Count: 0
    }
}

The above code shows how to use empty()the method to create an empty stream. Call the method directly Stream.empty()to get an empty stream that does not contain any elements. Next, use count()the method to get the number of elements in the stream, since the stream is empty, the return value is 0. Finally print it out.

Note that since the stream contains no elements, any operations on it will have no effect and will not raise any exceptions.

generate(Supplier<T> s)

generate()The method is Streama static method in the class that takes a Supplierfunction as an argument to generate the sequence of elements. generate()method will generate elements infinitely according to the logic of the generating function, until the upper limit of the stream is reached or interrupted by the user.

For example, suppose you need to generate a stream of random integers, you can use generate()the method:

Random random = new Random();
Stream<Integer> intStream = Stream.generate(() -> random.nextInt(100));

RandomIn the above code, a object is first created to generate random integers, then Stream.generate()a new stream is created through the method, and a generator function is passed in () -> random.nextInt(100)to generate random integers. Since generate()the method does not limit the number of elements, this stream will continue to generate random integers until it is forced to stop.

It should be noted that since generate()the stream generated by the method is infinite, if the stream is not limited, the program may fall into an infinite loop or memory overflow and other problems. If you need to convert the stream to a stream of finite length, you can use limit()the method or takeWhile()method.

Also, since generate()the method is a static method, it can be called from anywhere to create a new stream. At the same time, since the generating function is stateless, elements can be generated in parallel to improve efficiency.

iterate(T seed, UnaryOperator<T> f)

iterate()method is Streama static method in the class that takes as parameters a starting element and a unary operation function to generate a stream of infinitely consecutive elements. iterate()The method takes the starting element as the first element of the sequence, and based on this element, generates new elements continuously through the unary operation function.

For example, suppose you need to generate a stream containing Fibonacci numbers, you can use iterate()the method to achieve:

Stream.iterate(new int[]{0, 1}, arr -> new int[]{arr[1], arr[0] + arr[1]})
      .mapToInt(arr -> arr[0])
      .limit(10)
      .forEach(System.out::println);

In the above code, a starting element and a unary operation function are first Stream.iterate()defined through the method to generate the next Fibonacci sequence element. Then use the method to convert each element to the first number in the Fibonacci sequence, and use the method to limit the number of elements to 10. Finally, each element is output to the console via the method.{0, 1}arr -> new int[]{arr[1], arr[0] + arr[1]}mapToInt()limit()forEach()

It should be noted that since iterate()the stream generated by the method is infinite, if the stream is not limited, the program may fall into an infinite loop or memory overflow and other problems. If you need to convert the stream to a stream of finite length, you can use limit()the method or takeWhile()method.

Also, since unary operations are stateless, elements can be generated in parallel for greater efficiency. At the same time, since iterate()the stream generated by the method is ordered, it is not recommended to use it in parallel streams.

 concat(Stream<? extends T> a, Stream<? extends T> b)

StreamThe static method in the interface concat(Stream<? extends T> a, Stream<? extends T> b)can connect two streams to form a new stream. This new stream contains all the elements of the two original streams, first in the order of the first stream, and then in the order of the second stream.

Here is an example of usage:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamConcatExample {
    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("A", "B", "C");
        List<String> list2 = Arrays.asList("D", "E", "F");

        Stream<String> stream1 = list1.stream();
        Stream<String> stream2 = list2.stream();

        Stream<String> concatStream = Stream.concat(stream1, stream2);

        List<String> result = concatStream.collect(Collectors.toList());

        System.out.println(result); // [A, B, C, D, E, F]
    }
}

The above code shows concat()an example of how to concatenate two lists of strings using the method. list1First, two lists and are created list2, and then stream()they are converted into streams by the method, resulting in two streams stream1and stream2. Then, concat(stream1, stream2)connect the two streams through the method to get a new stream concatStreamthat contains all the elements in the two original streams. Finally, collect(Collectors.toList())the elements in this new stream are collected into a list via the method, resulting in a list containing all elements result.

It should be noted that when using concat()the method, it is necessary to ensure that the element types in the two streams are the same. In addition, once a stream has been manipulated, such as using methods such as filter, mapetc., then the stream cannot be connected, otherwise IllegalStateExceptionan exception will be thrown.

 builder()

Used to create mutables that support adding elements Stream.

Here is builder()an example usage of the method:

Stream<String> stream = Stream.<String>builder()
        .add("apple")
        .add("banana")
        .add("orange")
        .build();

stream.forEach(System.out::println);

In the above code, an object is first created with Stream.builder()and Stream.Builderthen add()three string elements are added to the object with the method. build()Finally, a new object is created by calling the method Stream, and forEach()its elements are output using the method.

It should be noted that since is mutable, the method should only be used to create objects Stream.Builderwhen necessary . In other cases, objects should be created using immutable collections or arrays to avoid concurrency problems.builder()StreamStream

 ofNullable(T t)

The Stream class in Java 8 provides the ofNullable(T t) method for creating a stream object containing zero or one elements. This method accepts a parameter t of type T, which can be any object, including null. If the parameter t is not null, then a stream of length 1 containing the element will be created; otherwise, an empty stream will be created, ie containing no elements.

This method returns an Optional object, and the corresponding Stream object can be obtained by calling its stream() method. If the parameter t is not null, the stream object contains exactly one element t; otherwise, the stream object is empty.

For example, we can use the ofNullable(T t) method to determine whether an object is null and convert it to a stream object. For example:

String str = null;
Stream<String> stream = Stream.ofNullable(str);
 
  

The above code will create an empty stream object stream because str is null. If str is non-null, a stream object is created containing the elements of str.

The ofNullable(T t) method is usually used to deal with situations where the data source is empty. For example, in streaming computing, when the data source is empty, special processing is required. In this case, the ofNullable() method can be used to convert it conveniently is an empty stream object. At the same time, this method can also be used to simplify some stream computing operations. For example, when using the filter() method to filter null values, you can use the ofNullable() method to convert null values ​​into empty stream objects before filtering.

In summary, the ofNullable(T t) method can conveniently convert an object into a stream object containing zero or one elements, which is usually used to handle null value cases and simplify encoding operations.

range(int startInclusive, int endExclusive)

range(int startInclusive, int endExclusive) is a static method provided by the Stream class in Java 8, which is used to create an integer sequence stream object from startInclusive (inclusive) to endExclusive (exclusive). This method returns an IntStream stream object, and various operations can be performed on the stream.

Here is an example showing how to use the range() method to create a sequence stream of integers:

IntStream intStream = IntStream.range(1, 10);
intStream.forEach(System.out::print); // 输出:123456789

In the above code, we use the range() method to create an integer sequence stream object from 1 to 10, and store it in the intStream variable. Then, we call the forEach() method of the intStream object, and use the method reference System.out::print to output each element in turn, thus obtaining the output results from 1 to 9.

It should be noted that the integer sequence stream object created by using the range() method does not contain the end value endExclusive, that is, the interval is left-closed and right-open. So, in the above example, the output is from 1 to 9, excluding the number 10.

rangeClosed(int startInclusive, int endInclusive) 

rangeClosed(int startInclusive, int endInclusive) is a static method provided by the Stream class in Java 8, which is used to create an integer sequence stream object from startInclusive (inclusive) to endInclusive (inclusive). This method returns an IntStream stream object, and various operations can be performed on the stream.

Here is an example showing how to use the rangeClosed() method to create a sequence stream of integers:

IntStream intStream = IntStream.rangeClosed(1, 10);
intStream.forEach(System.out::print); // 输出:12345678910

In the above code, we use the rangeClosed() method to create an integer sequence stream object from 1 to 10 and store it in the intStream variable. Then, we call the forEach() method of the intStream object, and use the method reference System.out::print to output each element in turn, thus obtaining the output results from 1 to 10.

It should be noted that the integer sequence stream object created by using the rangeClosed() method contains the end value endInclusive, that is, the range is left-closed and right-closed. So, in the above example, the output is from 1 to 10, including the number 10.

Guess you like

Origin blog.csdn.net/Ascend1977/article/details/131094779