Method description and combination examples of each stage in the Stream flow

Common methods

Stream method combination use

The first one introduces the operations that can be performed on string collections

import java.util.Arrays;
import java.util.List;

public class StreamExample {
    
    
    public static void main(String[] args) {
    
    
        List<String> list = Arrays.asList("apple", "banana", "cat", "dog", "egg");

        long count = list.stream()                  // 创建Stream
                        .filter(s -> s.length() == 3) // 过滤长度为3的元素
                        .map(String::toUpperCase)     // 转换为大写
                        .sorted()                     // 排序
                        .count();                     // 统计元素个数

        System.out.println(count); // 输出:3
    }
}

In the above code, a List containing 5 strings is first created, and then converted into a Stream through the stream() method. Then perform operations on the Stream, including filtering, converting to uppercase, sorting and counting the number of elements. Finally, print out the statistical results.
The specific steps and notes are as follows:

  • list.stream(): Convert List to a Stream object.
  • filter(s -> s.length() == 3): Filter the elements in the Stream and only retain elements with a length of 3.
  • map(String::toUpperCase): Convert the elements in the Stream to uppercase.
  • sorted(): Sorts the elements in the Stream.
  • count(): Counts the number of elements in the Stream.
  • System.out.println(count): Print out the statistical results.

The second type introduces the operations that can be performed on int type collections

The following code demonstrates how to use Stream's method combination to complete the following three operations:

Find all even numbers greater than 5 and store the results in a list;
calculate the sum of the squares of all elements in the list;
find the maximum and minimum values ​​in the list.

import java.util.Arrays;
import java.util.List;

public class StreamDemo {
    
    

    public static void main(String[] args) {
    
    
        // 创建一个包含整数的列表
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // 找出所有大于5的偶数,并将结果存储到一个列表中
        List<Integer> result = numbers.stream()
                .filter(n -> n > 5)          // 过滤出大于5的数
                .filter(n -> n % 2 == 0)    // 过滤出偶数
                .collect(Collectors.toList()); // 将结果存储到一个列表中

        System.out.println(result);

        // 计算列表中所有元素的平方和
        int sum = numbers.stream()
                .mapToInt(n -> n * n)        // 将元素映射为它的平方
                .sum();                     // 计算和

        System.out.println(sum);

        // 找出列表中的最大值和最小值
        IntSummaryStatistics stats = numbers.stream()
                .mapToInt((x) -> x)          // 将Stream<Integer>转换为IntStream
                .summaryStatistics();       // 计算统计信息

        System.out.println("最大值: " + stats.getMax());
        System.out.println("最小值: " + stats.getMin());
    }
}

These three operations are explained in detail below:

Operation 1: Find all even numbers greater than 5 and store the results into a list

First, use the filter() method to filter out numbers greater than 5, then use another filter() method to filter out even numbers, and finally use the collect() method to store the results into a list.

Operation 2: Calculate the sum of squares of all elements in the list

First, each element is mapped to its square using the mapToInt() method, and then the sum is calculated using the sum() method.

Operation 3: Find the maximum and minimum value in the list

First, use the mapToInt() method to convert the Stream to an IntStream, and then use the summaryStatistics() method to calculate statistics, including maximum and minimum values.

The third method introduces the use of the combination of collect() and filter()

In the code below, a List containing the numbers 1 to 10 is first created. Then, call the stream() method to convert the List into a Stream. Then, call the filter() method to filter the elements in the Stream, retaining only even elements. Finally, call the collect() method to collect the results into a new List.

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

public class StreamDemo {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        List<Integer> result = numbers.stream()
                .filter(number -> number % 2 == 0)
                .collect(Collectors.toList());

        System.out.println(result);
    }
}

Convert a List containing student information into a Map with student names as keys and student objects as values.
In the code below, a List containing three student information is first created. Then, call the stream() method to convert the List into a Stream. Next, call the collect() method, passing a Collectors.toMap() method as a parameter. In the toMap() method, use Student::getName to use the student name as the key of the Map, and use student -> student to use the student object as the value of the Map. Finally, the results are stored in a Map object.

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

public class StreamDemo {
    
    

    public static void main(String[] args) {
    
    
        List<Student> students = Arrays.asList(
                new Student("Tom", 18),
                new Student("Jack", 20),
                new Student("Lucy", 19)
        );

        Map<String, Student> result = students.stream()
                .collect(Collectors.toMap(Student::getName, student -> student));

        System.out.println(result);
    }
}

class Student {
    
    
    private String name;
    private int age;

    public Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    public String getName() {
    
    
        return name;
    }

    public int getAge() {
    
    
        return age;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Method comparison between flatMap() and filter()

Both methods can be used to filter data in streams, but their implementation and functions are different.
The function of the flatMap() method is to convert each element in a Stream into a new stream, and then merge these streams into a new stream. In other words, the flatMap() method is used to process nested stream structures and flatten them into a single stream. Therefore, the flatMap() method is often used to expand nested collections or arrays into a separate stream to facilitate further processing.
Here is an example code using the flatMap() method:

List<List<Integer>> numbers = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6));
List<Integer> flattenedNumbers = numbers.stream()
        .flatMap(Collection::stream)
        .collect(Collectors.toList());
System.out.println(flattenedNumbers);
// Output: [1, 2, 3, 4, 5, 6]

In the above code, a list numbers containing multiple collections is first created. Then, call the stream() method to convert this list into a Stream. Next, use the flatMap() method to convert each collection into a new stream, and merge the streams into a new stream. Finally, use the collect() method to collect all elements into a new List.
The function of the filter() method is to filter out elements that meet the conditions based on the specified conditions and collect them into a new Stream. In other words, the filter() method is used to conditionally filter elements in the Stream. Therefore, the filter() method is often used to select elements that meet conditions from a large data collection for further processing.
Here is a sample code using the filter() method:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> evenNumbers = numbers.stream()
        .filter(n -> n % 2 == 0)
        .collect(Collectors.toList());
System.out.println(evenNumbers);
// Output: [2, 4, 6]

In the above code, a list of numbers containing multiple integers is first created. Then, call the stream() method to convert this list into a Stream. Next, use the filter() method to filter out all even numbers and collect them into a new Stream. Finally, use the collect() method to collect all even numbers into a new List.
It should be noted that the flatMap() and filter() methods are both used to process data in a Stream and return a new Stream. They are often used in combination to achieve more complex processing of data.

Creation of Stream

A Stream can be created in the following ways:

1. Create from a collection or array

Stream can be created through Collection.stream() or Arrays.stream() method.

List<String> list = Arrays.asList("a", "b", "c"); 
Stream<String> stream = list.stream();

2. Create using Stream.of()

Create a Stream using the Stream.of() method.

Stream<String> stream = Stream.of("a", "b", "c");

3. Create using Stream.iterate()

Create an infinite stream using the Stream.iterate() method.

Stream<Integer> stream = Stream.iterate(0, n -> n + 2);

4. Create using Stream.generate()

Create an infinite stream using the Stream.generate() method.

Stream<Double> stream = Stream.generate(Math::random);

Stream intermediate operations

Intermediate operations refer to operations that process the data source and return a Stream object. The data source can be filtered, mapped, deduplicated, sorted, etc.

The following are commonly used Stream intermediate operations:

1. filter

This method is used to filter out elements according to the set conditions and return a new Stream object.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear"); 
stream.filter(s -> s.length() > 5).forEach(System.out::println);

2. map

This method is used to convert elements according to certain rules and return a new Stream object.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear"); 
stream.map(String::toUpperCase).forEach(System.out::println);

3. flatMap

This method is used to convert each element in a Stream to another Stream, then merge all elements in the Stream into a Stream, and return a new Stream object.
Specifically, the flatMap() method receives a function as a parameter, which converts an element into a new stream. Then, the flatMap() method merges all these new streams into a new stream, and finally returns this new stream. If this function returns an empty stream, then the stream will not contain any elements.

Stream<List<Integer>> stream = Stream.of(Arrays.asList(1, 2), Arrays.asList(3, 4)); 
stream.flatMap(Collection::stream).forEach(System.out::println);

4. distinct

This method is used to deduplicate elements in the Stream and return a new Stream object.

Stream<String> stream = Stream.of("apple", "banana", "orange", "apple"); 
stream.distinct().forEach(System.out::println);

5. sorted

This method is used to sort the elements in the Stream and return a new Stream object.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear"); 
stream.sorted().forEach(System.out::println);

6. peek

This method is used to operate on elements when performing the next operation in the Stream, returning a new Stream object.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear"); 
stream.peek(s -> System.out.println("before filter: " + s)).filter(s -> s.length() > 5) .peek(s -> System.out.println("after filter: " + s)).forEach(System.out::println);

7. limit

This method is used to intercept the first n elements in the Stream and return a new Stream object.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear"); 
stream.limit(2).forEach(System.out::println);

8. skip

This method is used to skip the first n elements in the Stream and return a new Stream object.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear"); 
stream.skip(2).forEach(System.out::println);

9. parallel

This method is used to convert a Stream into a parallel stream and return a new Stream object.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear"); 
stream.parallel().forEach(System.out::println);

10. sequential

This method is used to convert a Stream into a serial stream and return a new Stream object.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear"); 
stream.parallel().sequential().forEach(System.out::println);

Stream termination operation

The termination operation refers to the final operation on the Stream, which produces a result or side effect, but no longer returns a Stream object.

The following are commonly used Stream termination operations:

1. forEach

This method is used to traverse the elements in the Stream.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear"); 
stream.forEach(System.out::println);

2. toArray

This method is used to convert the elements in the Stream to an array.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear");
 String[] strArr = stream.toArray(String[]::new);

3. reduce

This method is used to reduce all elements in the Stream according to the specified rules and return an Optional object.

Stream<Integer> stream = Stream.of(1, 2, 3, 4); Optional<Integer> result = stream.reduce((x, y) -> x + y); 
result.ifPresent(System.out::println);

4. collect

This method is used to collect elements in the Stream into a collection and return a new collection object.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear"); List<String> list = stream.collect(Collectors.toList());

5. count

This method is used to count the number of elements in the Stream and returns a long type value.

Stream<String> stream = Stream.of("apple", "banana", "orange", "pear");
long count = stream.count();
System.out.println(count);

6. anyMatch

This method is used to determine whether there are elements in the Stream that meet the specified conditions and returns a boolean value.

Stream<Integer> stream = Stream.of(1, 2, 3, 4); boolean result = stream.anyMatch(x -> x > 2); 
System.out.println(result);

7. allMatch

This method is used to determine whether all elements in the Stream meet the specified conditions and returns a boolean value.

Stream<Integer> stream = Stream.of(1, 2, 3, 4); boolean result = stream.allMatch(x -> x > 0); 
System.out.println(result);

8. noneMatch

This method is used to determine whether all elements in the Stream do not meet the specified conditions and returns a boolean value.

Stream<Integer> stream = Stream.of(1, 2, 3, 4); boolean result = stream.noneMatch(x -> x > 5); 
System.out.println(result);

9. findAny

This method is used to obtain any element in the Stream and returns an Optional object.

Stream<Integer> stream = Stream.of(1, 2, 3, 4); Optional<Integer> result = stream.findAny(); 
result.ifPresent(System.out::println);

10. findFirst

This method is used to get the first element in the Stream and returns an Optional object.

​​

Stream<Integer> stream = Stream.of(1, 2, 3, 4); Optional<Integer> result = stream.findFirst(); 
result.ifPresent(System.out::println);

Guess you like

Origin blog.csdn.net/pengjun_ge/article/details/130406016