Technology Sharing

How to use Java Stream API to simplify collection operations?

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

How to use Java Stream API to simplify collection operations?

Hello everyone, I am the editor of Weizhuan Taobao Affiliate System 3.0, and I am also a programmer who doesn’t wear thermal underwear in winter and wants to be graceful even when it’s cold!

Java Stream API is a new abstract concept introduced in Java 8 for performing functional-style operations on collection objects. It allows us to process collection data in a more concise and readable way, including operations such as screening, mapping, filtering, and sorting.

Stream creation and basic operations

Using the Stream API, we can create Streams in various ways, such as collection conversion, array conversion, etc. The following are some basic Stream operation examples:

package cn.juwatech.stream;

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

public class StreamExample {

    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eva");

        // 筛选名字长度大于3的人,并转换为大写
        List<String> filteredNames = names.stream()
                .filter(name -> name.length() > 3)
                .map(String::toUpperCase)
                .collect(Collectors.toList());

        System.out.println("Filtered and transformed names: " + filteredNames);

        // 计算所有名字长度的总和
        int totalLength = names.stream()
                .mapToInt(String::length)
                .sum();

        System.out.println("Total length of all names: " + totalLength);

        // 判断集合中是否存在名字以'A'开头的
        boolean anyStartsWithA = names.stream()
                .anyMatch(name -> name.startsWith("A"));

        System.out.println("Any name starts with 'A'? " + anyStartsWithA);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

Advanced Stream Operations

In addition to the basic filter, map, and reduce operations, the Stream API also provides a wealth of advanced operations, such as sorting, grouping, and deduplication. The following are some examples of advanced operations:

package cn.juwatech.stream;

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

public class AdvancedStreamOperations {

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

        // 对数字进行平方映射,然后筛选出大于20的数字,并按降序排序
        List<Integer> result = numbers.stream()
                .map(n -> n * n)
                .filter(n -> n > 20)
                .sorted((a, b) -> b - a)
                .collect(Collectors.toList());

        System.out.println("Result after mapping, filtering, and sorting: " + result);

        // 将字符串列表拼接成一个字符串
        List<String> words = Arrays.asList("Java", "Stream", "API", "is", "awesome");

        String concatenatedString = words.stream()
                .collect(Collectors.joining(" "));

        System.out.println("Concatenated string: " + concatenatedString);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

Parallel Stream Operations

Stream API also supports parallel processing, which can significantly improve the running efficiency on multi-core CPUs. We can callparallel()Method converts a sequential stream into a parallel stream.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eva");

// 并行处理:筛选名字长度大于3的人,并转换为大写
List<String> parallelFilteredNames = names.parallelStream()
        .filter(name -> name.length() > 3)
        .map(String::toUpperCase)
        .collect(Collectors.toList());

System.out.println("Parallel filtered and transformed names: " + parallelFilteredNames);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Conclusion

Through the introduction of this article, we have a deep understanding of the basic usage and advanced functions of Java Stream API. Stream API can not only simplify the collection operation code, but also improve the readability and maintainability of the code. It is an indispensable part of modern Java development.

Weizhuan Taoke System 3.0 is produced by the editor and is a high-quality product. Please indicate the source when reprinting!