No "if" statements, please, unless you're explaining why it's impossible to do without one.
I'm seeing how far I can go operating on streams only. I have this nuisance:
List<Cube> revised =
cubes.filter(p)
.map(c -> f(c))
.map(c -> {
if(c.prop()) {
c.addComment(comment);
}
return c;
})
.collect(Collectors.toList());
My best idea for how to do this without an "if" is
List<Cube> revised =
cubes.filter(p)
.map(c -> f(c));
revised
.filter(Cube::prop)
.forEach(c -> c.addComment(comment)); // can also map still
Is there a way to do this in one chain only? A branch basically has to happen in the stream if so. A method like forSome(predicate, lambda)
would work.
Do not want to "roll my own" anything. I can use an "if" but I'm trying to learn how expressive functional style can be.
The skip() MethodThe skip(n) method is an intermediate operation that discards the first n elements of a stream. The n parameter can't be negative, and if it's higher than the size of the stream, skip() returns an empty stream. When this stream is executed, the forEach starts asking for items.
The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection. The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
You can't.
There's no need to use map
that returns the same element, when you have peek
. The following code "cheats" by using a short-circuit operator:
cubes.filter(p)
.map(c -> f(c))
.peek(c -> c.prop() && c.addComment(comment))
I think the "modern" way using Optional is far less readable:
cubes.filter(p)
.map(c -> f(c))
.peek(c -> Optional.of(c).filter(Cube::prop).ifPresent(c -> c.addComment(comment)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With