Home > Java > javaTutorial > body text

How the Java Stream API makes your code better

王林
Release: 2023-05-14 18:22:06
forward
703 people have browsed it

    前言

    Java Stream 是一种强大的数据处理工具,可以帮助开发人员快速高效地处理和转换数据流。使用 Stream 操作可以大大简化代码,使其更具可读性和可维护性,从而提高开发效率。

    • filter():根据指定的 Predicate 保留符合条件的元素。

    • map():根据指定的 Function 映射每个元素,生成一个新的 Stream。

    • flatMap():将每个元素映射为一个 Stream,然后将这些 Stream 连接成一个 Stream。

    • distinct():返回一个去重后的 Stream。

    • sorted():对 Stream 进行排序。

    • peek():对每个元素执行指定的操作,但并不消费元素。

    • limit():返回一个截断后的 Stream。

    • skip():返回一个跳过指定元素后的 Stream。

    • forEach():对每个元素执行指定的操作。

    • toArray():将 Stream 转换为数组。

    示例

    示例 1:使用 filter() 方法过滤奇数

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            List<Integer> evenNumbers = numbers.stream()
                    .filter(n -> n % 2 == 0)
                    .collect(Collectors.toList());
            System.out.println("Even numbers: " + evenNumbers);
        }
    }
    Copy after login

    输出结果:

    Even numbers: [2, 4, 6, 8, 10]

    示例 2:使用 map() 方法将每个字符串转换为大写

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public static void main(String[] args) {
            List<String> words = Arrays.asList("hello", "world", "java", "stream");
            List<String> capitalizedWords = words.stream()
                    .map(String::toUpperCase)
                    .collect(Collectors.toList());
            System.out.println("Capitalized words: " + capitalizedWords);
        }
    }
    Copy after login

    输出结果:

    Capitalized words: [HELLO, WORLD, JAVA, STREAM]

    示例 3:使用 flatMap() 方法将嵌套的列表展平为一个列表

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public static void main(String[] args) {
            List<List<Integer>> nestedNumbers = Arrays.asList(
                    Arrays.asList(1, 2),
                    Arrays.asList(3, 4, 5),
                    Arrays.asList(6, 7, 8, 9)
            );
            List<Integer> flattenedNumbers = nestedNumbers.stream()
                    .flatMap(List::stream)
                    .collect(Collectors.toList());
            System.out.println("Flattened numbers: " + flattenedNumbers);
        }
    }
    Copy after login

    输出结果:

    Flattened numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9]

    示例 4:使用 distinct() 方法去除重复元素

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public static void main(String[] args) {
            List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 2, 1, 4, 5, 4, 3, 6);
            List&lt;Integer&gt; distinctNumbers = numbers.stream()
                    .distinct()
                    .collect(Collectors.toList());
            System.out.println("Distinct numbers: " + distinctNumbers);
        }
    }
    Copy after login

    输出结果:

    Distinct numbers: [1, 2, 3, 4, 5, 6]

    示例 5:使用 sorted() 方法对 Stream 进行排序

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(5, 3, 8, 2, 9, 1, 7, 4, 6, 10);
            List<Integer> sortedNumbers = numbers.stream()
                    .sorted()
                    .collect(Collectors.toList());
            System.out.println("Sorted numbers: " + sortedNumbers);
        }
    }
    Copy after login

    输出结果:

    Sorted numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    示例 6:使用 peek() 方法打印每个元素并统计元素个数

    import java.util.Arrays;
    import java.util.List;
    public class Example {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            int count = numbers.stream()
                    .peek(System.out::println)
                    .mapToInt(Integer::intValue)
                    .sum();
            System.out.println("Total count: " + count);
        }
    }
    Copy after login

    输出结果:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Total count: 55

    示例 7:使用 limit() 方法限制结果集大小

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            List<Integer> limitedNumbers = numbers.stream()
                    .limit(5)
                    .collect(Collectors.toList());
            System.out.println("Limited numbers: " + limitedNumbers);
        }
    }
    Copy after login

    输出结果:

    Limited numbers: [1, 2, 3, 4, 5]

    示例 8:使用 skip() 方法跳过前面的元素

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            List<Integer> skippedNumbers = numbers.stream()
                    .skip(5)
                    .collect(Collectors.toList());
            System.out.println("Skipped numbers: " + skippedNumbers);
        }
    }
    Copy after login

    输出结果:

    Skipped numbers: [6, 7, 8, 9, 10]

    示例 9:使用 forEach() 方法打印每个元素

    import java.util.Arrays;
    import java.util.List;
    public class Example {
        public static void main(String[] args) {
            List&lt;String&gt; words = Arrays.asList("hello", "world", "java", "stream");
            words.stream()
                    .forEach(System.out::println);
        }
    }
    Copy after login

    输出结果:

    hello
    world
    java
    stream

    示例 10:使用 toArray() 方法将 Stream 转换为数组

    import java.util.Arrays;
    import java.util.List;
    public class Example {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            Integer[] numberArray = numbers.stream()
                    .toArray(Integer[]::new);
            System.out.println("Number array: " + Arrays.toString(numberArray));
        }
    }
    Copy after login

    输出结果:

    Number array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    The above is the detailed content of How the Java Stream API makes your code better. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template