How to Use if/else Logic in Java 8 Streams – 如何在Java 8流中使用if/else逻辑

最后修改: 2018年 10月 10日

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

1. Overview

1.概述

In this tutorial, we’re going to demonstrate how to implement if/else logic with Java 8 Streams. As part of the tutorial, we’ll create a simple algorithm to identify odd and even numbers.

在本教程中,我们将演示如何用Java 8 Streams实现if/else逻辑。作为本教程的一部分,我们将创建一个简单的算法来识别奇数和偶数。

We can take a look at this article to catch up on the Java 8 Stream basics.

我们可以看看这篇文章,了解一下Java 8的Stream基础知识。

2. Conventional if/else Logic Within forEach()

2.传统的if/else逻辑在forEach()中的应用

First of all, let’s create an Integer List and then use conventional if/else logic within the Integer stream forEach() method:

首先,让我们创建一个Integer List ,然后在IntegerforEach()方法中使用常规的if/else逻辑。

List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

ints.stream()
    .forEach(i -> {
        if (i.intValue() % 2 == 0) {
            Assert.assertTrue(i.intValue() % 2 == 0);
        } else {
            Assert.assertTrue(i.intValue() % 2 != 0);
        }
    });

Our forEach method contains if-else logic which verifies whether the Integer is an odd or even number using the Java modulus operator.

我们的forEach方法包含if-else逻辑,该逻辑使用Java模数运算符验证Integer是奇数还是偶数

3. if/else Logic With filter()

3.if/else逻辑与filter()

Secondly, let’s look at a more elegant implementation using the Stream filter() method:

其次,让我们看一下使用Stream filter()方法的更优雅的实现。

Stream<Integer> evenIntegers = ints.stream()
    .filter(i -> i.intValue() % 2 == 0);
Stream<Integer> oddIntegers = ints.stream()
    .filter(i -> i.intValue() % 2 != 0);

evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() % 2 == 0));
oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() % 2 != 0));

Above we implemented the if/else logic using the Stream filter() method to separate the Integer List into two Streams, one for even integers and another for odd integers.

上面我们使用Stream filter()方法实现了if/else逻辑,Integer List分成两个Streams,一个用于偶数整数,另一个用于奇数整数。

4. Conclusion

4.结论

In this quick article, we’ve explored how to create a Java 8 Stream and how to implement if/else logic using the forEach() method.

在这篇快速文章中,我们探讨了如何创建一个Java 8 Stream以及如何使用forEach()方法实现if/else逻辑。

Furthermore, we learned how to use the Stream filter method to achieve a similar result, in a more elegant manner.

此外,我们学会了如何使用Stream filter方法,以更优雅的方式实现类似的结果。

Finally, the complete source code used in this tutorial is available over on Github.

最后,本教程中所使用的完整源代码可在Github上获得