Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 forEach applied to only some?

Tags:

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.

like image 346
djechlin Avatar asked Oct 13 '17 14:10

djechlin


People also ask

How do I skip forEach in Java 8?

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.

Why forEach method is added to each collection?

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.

Can we break forEach loop in Java?

You can't.


1 Answers

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)))
like image 73
DodgyCodeException Avatar answered Oct 11 '22 12:10

DodgyCodeException