Implementing if / else logic in Java 8 stream expressions

brief introduction

In stream processing, we usually encounter the judgment of if / else. How do we deal with such problems?

Remember that we mentioned in the previous article lambda best practices that lambda expressions should be as concise as possible, and do not write bloated business logic in them.

Next, let's look at a specific example.

Traditional writing

If we have a list of 1 to 10, we want to select odd and even numbers respectively. In the traditional way, we will use this:

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

        ints.stream()
                .forEach(i -> {
                    if (i.intValue() % 2 == 0) {
                        System.out.println("i is even");
                    } else {
                        System.out.println("i is old");
                    }
                });
    }

In the above example, we put the logic of if / else into foreach. Although there is no problem, the code is very bloated.

Let's see how to rewrite it.

Using filter

We can rewrite the logic of if / else into two filters:

List<Integer> ints = Arrays.asList(1,10);

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

With these two filters, use for each in the stream after the filter:

        evenIntegers.forEach(i -> System.out.println("i is even"));
        oddIntegers.forEach(i -> System.out.println("i is old"));

How, is the code very concise and clear.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>