How to use Stream API in Java?

What is the Stream API?

The Stream API is a new feature introduced in Java 8 that provides a functional way of streaming collection data. The Stream API allows us to process collection data in a more concise and readable way, and at the same time, it can make full use of the parallel processing capabilities of multi-core CPUs to improve program execution efficiency.

In the Stream API, we can process collection data through a series of operations, which can be divided into intermediate operations and termination operations. The intermediate operation is to process and transform the data of the stream, but will not produce the final result; the termination operation is the operation that produces the final result, which will trigger the processing of the stream and return the result.

Stream API mainly includes the following parts:

  • Creation of streams: Create streams through collections, arrays, files, etc.
  • Operation flow: perform operations such as filtering, mapping, sorting, and deduplication on the flow.
  • Terminate streams: Convert streams to collections, arrays, summary statistics, match checks, etc.

Below we will introduce in detail how to use the Stream API in Java.

insert image description here

How to use Stream API in Java?

stream creation

In Java, we can create streams in several ways. Here are some common ways to create streams:

Create a stream from a collection

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

Create a stream from an array

int[] array = {
    
    1, 2, 3, 4, 5};
IntStream stream = Arrays.stream(array);

Create a stream from a file

Path path = Paths.get("file.txt");
Stream<String> stream = Files.lines(path);

Create a stream from a function

Stream.generate(() -> "hello")
      .limit(5)
      .forEach(System.out::println);

In the above code, we use the Stream.generate() method to create an infinite stream, which will continuously generate the string "hello", and then use the limit() method to intercept the stream, and finally output the first 5 elements.

operation flow

After creating the stream, we can perform a series of operations on the stream to realize data processing and transformation. Here are some commonly used stream operations:

filter() method

The filter() method can filter the data in the stream, and only keep the qualified data, so as to get a new stream.

List<String> list = Arrays.asList("a", "b", "c", "d");
Stream<String> stream = list.stream().filter(s -> s.startsWith("a"));

In the above code, we use the filter() method to filter out the strings starting with "a" and get a new stream.

map() method

The map() method can transform the data in the stream to get a new stream.

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

In the above code, we use the map() method to convert the string to uppercase and get a new stream.

sorted() method

The sorted() method can sort the data in the stream to get a new stream.

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

In the above code, we use the sorted() method to sort the strings and get a new stream.

distinct() method

The distinct() method can deduplicate the data in the stream to obtain a new stream.

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

In the above code, we use the distinct() method to deduplicate the string and get a new stream.

peek() method

The peek() method can operate on the data in the stream without changing the data in the stream, but it can output some information during the operation.

List<String> list = Arrays.asList("a", "b", "c", "d");
Stream<String> stream = list.stream().peek(System.out::println);

In the above code, we use the peek() method to operate on the string and output the value of the string, but the data in the stream will not be changed.

terminate flow

After operating on the stream, we can transform the stream into a final result by terminating the operation. The following are some commonly used termination operations:

collect() method

The collect() method can collect the elements in the stream into a collection, such as List, Set, Map, etc.

List<String> list = Arrays.asList("a", "b", "c", "d");
List<String> result = list.stream().collect(Collectors.toList());

In the above code, we use the collect() method to collect the elements in the stream into a List.

reduce() method

The reduce() method can perform operations such as accumulation and summation on the elements in the stream to obtain a final result.

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int sum = list.stream().reduce(0, Integer::sum);

In the above code, we use the reduce() method to sum the integers and get the final result.

count() method

The count() method can count the number of elements in the stream.

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

In the above code, we use the count() method to count the number of elements in the stream.

forEach() method

The forEach() method can operate on each element in the stream, such as outputting to the console, etc.

List<String> list = Arrays.asList("a", "b", "c", "d");
list.stream().forEach(System.out::println);

In the code above, we output each element in the stream using the forEach() method.

Complete sample code

Below is a complete sample code that demonstrates how to use the Stream API to operate on data in a collection.

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

public class StreamDemo {
    
    
    public static void main(String[] args) {
    
    
        List<String> list = Arrays.asList("hello", "world", "java", "stream", "api");

        // 过滤出长度大于 4 的字符串,并将其转换成大写形式
        List<String> result = list.stream()
                .filter(s -> s.length() > 4)
                .map(String::toUpperCase)
                .collect(Collectors.toList());
        System.out.println(result);

        // 统计字符串的个数
        long count = list.stream().count();
        System.out.println(count);

        // 对字符串进行排序,并输出到控制台
        list.stream().sorted().forEach(System.out::println);

        // 对字符串进行去重,并输出到控制台
        list.stream().distinct().forEach(System.out::println);

        // 对字符串进行操作,并输出到控制台
        list.stream().peek(System.out::println).collect(Collectors.toList());
    }
}

The above code demonstrates how to use the Stream API to operate on the data in the collection and output the result to the console.

Summarize

The Stream API is a new feature introduced in Java 8 that provides a functional way of streaming collection data. Stream API allows us to process collection data in a more concise and readable way, and at the same time, it can make full use of the parallel processing capabilities of multi-core CPUs to improve program execution efficiency. When using the Stream API, we can process collection data through a series of operations, which can be divided into intermediate operations and termination operations. The intermediate operation is to process and transform the data of the stream, but will not produce the final result; the termination operation is the operation that produces the final result, which will trigger the processing of the stream and return the result. By using the Stream API, we can process and convert collection data more conveniently, and improve the readability and maintainability of the program.

Guess you like

Origin blog.csdn.net/JasonXu94/article/details/131760286