Java 8 Stream Operation on the Empty List – Java 8 空列表上的流操作

最后修改: 2024年 1月 11日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.导言

Java 8 brought a paradigm shift in the way we handle collections and data manipulation with the introduction of Streams. Stream APIs offer a concise and expressive way to perform operations on data, enabling developers to write more readable, robust, and efficient code.

Java 8 通过 引入 Streams 使我们处理集合和数据操作的方式发生了范式转变。Stream API 提供了一种简洁而富有表现力的方式来执行数据操作,从而使开发人员能够编写更可读、更健壮和更高效的代码。

In this tutorial, we’ll delve into the interesting world of Stream operations, focusing on the empty List. Although working with an empty List might seem trivial, it unveils some powerful aspects of the Stream API.

在本教程中,我们将深入 Stream 操作的有趣世界,重点关注空 List 操作。虽然使用空 List 看起来微不足道,但它揭示了 Stream API 的某些强大方面。

2. Converting an Empty List to a Stream

2.将空列表转换为流</em

We can easily obtain a Stream from an empty List using the stream() method:

我们可以使用 stream() 方法从空 List 中轻松获取 Stream

List<String> emptyList = new ArrayList<>();
Stream<String> emptyStream = emptyList.stream();

This enables us to perform various Stream operations on an empty List just as on a non-empty List. However, we must note that the result of the operation could be empty since the source of the Stream is empty. Furthermore, it could be interesting to explore more about working with empty Stream in Java.

这使我们能够在空 List 上执行各种 Stream 操作,就像在非空 List 上一样。但是,我们必须注意,由于 Stream 的源是空的,因此操作的结果可能是空的。此外,探索有关 在 Java 中使用空 Stream 的更多信息可能会很有趣。

3. Significance of an Empty Stream for Handling NullPointerException

3.空对处理NullPointerException的意义

One notable advantage of using Streams with empty Lists is the prevention of NullPointerExceptions. Let’s consider the following example, where the getList() method may return null:

Streams 与空 Lists 结合使用的一个显著优势是防止出现 NullPointerExceptions 异常。让我们来看看下面的示例,其中 getList() 方法可能会返回 null

List<String> nameList = getList(); // Assume getList() may return null

// Without Stream
if (nameList != null) {
    for (String str : nameList) {
        System.out.println("Length of " + name + ": " + name.length());
    }
}

Here, in the non-stream approach, we must check for null before iterating over the List to avoid a NullPointerException.

在非流方法中,我们必须在遍历 List 之前检查 null 以避免出现 NullPointerException 异常。

On the other hand, using Optional and Stream, we can perform a long chain of operations without specifically handling the null checks and also avoiding NullPointerException:

另一方面,使用可选项和流,我们可以执行一长串操作,而无需专门处理空检查,同时也避免了 NullPointerException

// With Stream
Optional.ofNullable(nameList)
  .ifPresent(list -> list.stream()
    .map(name -> "Length of " + name + ": " + name.length())
    .forEach(System.out::println));

Here, we’ve used Optional.ofNullable() to wrap nameList, preventing a NullPointerException if nameList is null. We then use the ifPresent() method to execute the Stream operations only if the list isn’t null.

在这里,我们使用 Optional.ofNullable() 封装 nameList,以防止在 nameListnull 时发生 NullPointerException 异常。然后,我们使用 ifPresent() 方法,只有当列表不是 null 时才执行 Stream 操作。

This ensures that the Stream operations are applied only when the List is non-null, preventing any potential NullPointerException. Moreover, the code is more concise, and operations on an empty Stream won’t result in any Exceptions or errors.

这将确保只有当 List 为非时,Stream 操作才会被应用,从而防止任何潜在的 NullPointerException 异常。此外,代码更加简洁,对空的操作不会导致任何异常或错误。

However, if the getList() method returns an empty List instead of a null, then with an empty Stream, the map() operation would get nothing to work upon. Hence, it results in a new empty Stream, leaving nothing to print in the forEach() call.

但是,如果 getList() 方法返回的是空 List 而不是空 null,那么在空 Stream 的情况下,map() 操作将一无所获。因此,它会产生一个新的空Stream,在forEach()调用中没有任何内容可打印。

In summary, both the traditional and Stream approaches aim to print the length of names from a List. The Stream approach, however, leverages Optional and Stream operations, providing a more functional and concise way to handle potential null values and empty Lists. This results in code that is both safer and more expressive.

总之,传统方法和 Stream 方法都旨在从 List 中打印名称的长度。然而,Stream 方法利用了 OptionalStream 操作,提供了一种功能更强、更简洁的方法来处理潜在的 null 值和空 Lists 。

4. Collecting a Stream of an Empty List Into Another List

4.将一个空 ListStream 收集到另一个 List

Stream offers a clean way to perform operations and collect results. Even when working with an empty List, we can utilize Stream operations and collectors effectively. Here’s a simple example of collecting elements from an empty List into another List through a Stream:

Stream 为执行操作和收集结果提供了一种简洁的方式。即使在处理空 List 时,我们也可以有效地使用 Stream 操作和收集器。下面是一个通过 Stream 将元素从空 List 收集到另一个 List 中的简单示例:

List<String> emptyList = new ArrayList<>();
List<String> collectedList = emptyList.stream().collect(Collectors.toList());

System.out.println(collectedList); // Output: []

Here, collect() is a terminal operation, and it performs mutable reduction on the elements of the Stream.

在这里,collect() 是一个终端操作,它对 Stream 中的元素执行可变还原。

Similarly, performing an intermediate operation such as filter() and collecting the result in any collection would result in an empty Stream:

同样,执行 filter() 等中间操作,并将结果收集到任何集合中,都会导致 Stream 为空:

List<String> emptyList = new ArrayList<>();
List<String> collectedList = emptyList.stream()
  .filter(s -> s.startsWith("a"))
  .collect(Collectors.toList());

This demonstrates that Stream operations on an empty List can be seamlessly integrated into collecting results without any issues.

这表明,对空 List 进行的 Stream 操作可以无缝集成到结果收集中,而不会出现任何问题。

5. Conclusion

5.结论

In conclusion, Java 8 Stream operations on an empty List showcase the elegance and robustness of the Stream API. The ability to effortlessly convert an empty List to a Stream, handle potential NullPointerExceptions more gracefully, and seamlessly perform operations such as collecting into another List makes Streams a powerful tool for developers.

总之,Java 8 对空 ListStream 操作展示了流 API 的优雅和健壮性。您可以毫不费力地将空 List 转换为 Stream,更优雅地处理潜在的 NullPointerException 并无缝地执行收集到另一个 List 等操作,这使 Stream 成为开发人员的强大工具。

By understanding and utilizing these features, developers can write more concise and expressive code, making the most out of the Stream API, even when dealing with empty Lists.

通过了解和利用这些功能,开发人员可以编写更简洁、更具表现力的代码,即使在处理空 List 时也能充分利用流 API。

As always, the source code accompanying the article is available over on GitHub.

与往常一样,本文的源代码可在 GitHub 上获取。