The most detailed examples of using various methods of Java8 Stream in the whole network (3)

The output is: “The maximum element is 5”, because 5 is the largest element in the list. Note that the max() method returns an Optional object, so it is necessary to determine whether there is a maximum value before performing other operations.

The output is: “The minimum element is 1”, because 1 is the minimum element in the list. Note that the min() method returns an Optional object, so it is necessary to determine whether there is a minimum value before performing other operations.

The output is: “All the elements are odd numbers.”, because there are no even numbers in the given list. If there are even numbers in the list, the output will be “There are even numbers in the list.”.

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.

The output is:

Processing element: 1
1
Processing element: 2
2
Processing element: 3
3
Processing elements: 4
4
Processing element: 5
5

The above code creates a list of type Integer and converts it into a Stream object. Next, call the peek() method to perform operations on each element and print the processing information, and finally call the forEach() method to print the value of each element. Since the peek() method does not change the elements in the original Stream, the final output is exactly the same as the list before conversion.

accumulator, BinaryOperator combiner)”> reduce(U identity, BiFunction accumulator, BinaryOperator combiner)

The reduce(U identity, BiFunction accumulator, BinaryOperator combiner) method is a terminating operation that reduces all elements into a single result. This method receives three parameters: the first parameter is the initial value identity, the second parameter is the BiFunction function, which is used to convert each element into a certain type U, and perform cumulative operations with the previous partial result, and the third The parameter is the BinaryOperator function, which is used to combine all partial results to obtain the final result.

The specific usage is as follows:

  1. Create a Stream object containing multiple elements.
  2. Call the reduce(U identity, BiFunction accumulator, BinaryOperator combiner) method, and pass in an initial value, a BiFunction function and a BinaryOperator function.
  3. This method will perform the specified accumulate operation on the entire stream and return the result.

For example, the following code demonstrates how to use the reduce() method to calculate the sum of the lengths of all elements in a list of strings:

List<String> list = Arrays.asList("java", "python", "ruby");
int result = list.stream().reduce(0, (sum, str) -> sum + str.length(), Integer::sum);
System.out.println(result); // output 14

The above code creates a list of String types and converts it into a Stream object. Next call the reduce() method, specify an initial value of 0, add the length of each element to the initial value, and use the Integer::sum method to combine all partial results. Finally, print the result, because the reduce() method returns the basic data type, there is no need to use the isPresent() method to determine whether the result exists.

It should be noted that since this method can be operated in parallel, each partial result needs to be accumulated using the BiFunction function, and the final result needs to be combined using the BinaryOperator function. If there are multiple partial results in the stream, the BinaryOperator function is called to combine them into one result.

skip(long n)

The skip(long n) method is an intermediate operation that skips the first n elements and returns a new Stream object. If n is greater than the number of elements in the stream, an empty Stream object will be returned.

The specific usage is as follows:

  1. Create a Stream object containing multiple elements.
  2. Call the skip(long n) method and pass in the number n of elements to skip.
  3. This method returns a new Stream object containing the remaining elements from the original stream.

For example, the following code demonstrates how to use the skip() method to skip the first two elements in a string stream:

List<String> list = Arrays.asList("apple", "banana", "orange", "pear");
Stream<String> stream = list. stream(). skip(2);
stream.forEach(System.out::println); // output orange pear

The above code creates a list of String types and converts it into a Stream object. Next call the skip() method, specifying that the first two elements are to be skipped. This method returns a new Stream object containing the remaining elements from the original stream. Finally, use the forEach() method to traverse the new Stream object and output it to the console.

It should be noted that the Stream object is lazily evaluated, so the skip operation is not performed immediately when the skip() method is called, but skipped when the Stream object is traversed. Skipped elements are also not kept in memory, thus reducing memory consumption when working with large datasets.

comparator)”>sorted(Comparator comparator)

The sorted(Comparator comparator) method is an intermediate operation that sorts the elements of a Stream object and returns a new Stream object. This method uses the incoming Comparator function to customize the collation.

The specific usage is as follows:

  1. Create a Stream object containing multiple elements.
  2. Call the sorted(Comparator comparator) method and pass in a Comparator function.
  3. This method will use the passed Comparator function to sort the elements in the Stream object and return a new Stream object.

For example, the following code demonstrates how to sort a string stream using the sorted() method and the Comparator function:

List<String> list = Arrays.asList("java", "python", "ruby", "c++");
Stream<String> sortedStream = list. stream(). sorted((s1, s2) -> s1. length() - s2. length());
sortedStream.forEach(System.out::println); // output c++ java ruby python

The above code creates a list of String types and converts it into a Stream object. Next call the sorted() method and pass in a Comparator function that sorts the strings by their length. This method returns a new Stream object whose elements are sorted according to the specified rules. Finally, use the forEach() method to traverse the new Stream object and output it to the console.

It should be noted that the incoming Comparator function can be sorted according to any rules, and does not necessarily depend on the compareTo() method of the class to which the element belongs. Since the Stream object is lazily evaluated, the sorting operation is not performed immediately when the sorted() method is called, but is sorted when the Stream object is traversed.

toArray()

The toArray() method is a terminating operation that converts the elements in the Stream object into an array and returns it. This method does not receive any parameters and will return an array of Object type, which can be cast using generic type inference.

The specific usage is as follows:

  1. Create a Stream object containing multiple elements.
  2. Call the toArray() method.
  3. This method converts the elements in the Stream object into an array of Object type and returns the array.

For example, the following code demonstrates how to use the toArray() method to convert elements in a string stream to an array:

List<String> list = Arrays.asList("apple", "banana", "orange", "pear");
Object[] array = list. stream(). toArray();
System.out.println(Arrays.toString(array)); // output [apple, banana, orange, pear]

The above code creates a list of String types and converts it into a Stream object. Next, the toArray() method is called, which converts the elements in the Stream object into an array of Object type and returns the array. Finally, use the Arrays.toString() method to convert the array to a string and output it to the console.

It should be noted that since the toArray() method returns an array of Object type, it is necessary to use generic type inference for forced type conversion. For example, if you want to convert an element of type String to an array of type String, you can use the following code:

String[] strArray = list.stream().toArray(String[]::new);

Here, we use the form of method reference, and pass the constructor String[]::new as a parameter to the toArray() method, so as to convert the array of Object type into an array of String type.

The above code creates a list of String types and converts it into a Stream object. Next call the toArray() method and pass in a Lambda expression that creates an array of type String based on the given size. This method will use a Lambda expression to create a new array and convert the elements in the Stream object into the array. Finally, use the Arrays.toString() method to convert the array to a string and output it to the console.

It should be noted that since we need to create an array of a specified type, we need to use generics and perform type conversion. In the above example, we used the Lambda expression (size -> new String[size]) to create a new array of String type. According to the value of size, this expression will return an array of type String of the specified size.

The most detailed example of using each method of Java8 Stream in the whole network (1) – Ascend JF’s Blog – CSDN Blog

The most detailed example of using each method of Java8 Stream in the whole network (2) – Ascend JF’s Blog – CSDN Blog

syntaxbug.com © 2021 All Rights Reserved.