Java 8 Streams API functions

Coder3108 :

I am new to Java 8 Streams API. I was working with forEach and filter and noticed that the following piece of code can be modified with either to produce the same result. In that case, how are the two different and how to decide when to use which?

items.forEach(item -> {
    if (item.contains("B") {
        System.out.println(item);
    }
});
items
    .filter(item -> item.contains("B"))
    .forEach(System.out::println);
MC Emperor :

They have the same effect.

The difference is that the piece of code calling filter uses the stream's filtering operation, whereas forEach with the if statement uses a plain old if statement.

Which one to use depends on what style you want to apply, but the functional programming paradigm, the style of the latter piece of code, has become more popular recently.


I personally would use

items
    .filter(item -> item.contains("B"))
    .forEach(System.out::println);

as I find this much better readable.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=292413&siteId=1