Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Streams: conditionals to avoid repetition?

is there a way to achieve something similar like my code below, without having to avoid repeating myself while also keeping the processing low?

    List<String> alist = new ArrayList<>();
    alist.add("hello");
    alist.add("hello2");

    if(verbose) {
        alist.stream()
                .peek(System.out::println)
                .forEach(/*dostuff*/);
    }
    else {
        alist.stream().forEach(/*dostuff*/);
    }

As seen above, I'm forced to repeat myself by handling the stream in either the if or else case which looks kind of ugly if the stream becomes a bit longer.

There's the other option which in my opinion looks cleaner but should be worse performance wise as it compares the verbose-boolean for every item in the list.

    List<String> alist = new ArrayList<>();
    alist.add("helllo");
    alist.add("hello2");

    alist.stream()
            .peek(this::printVerbose)
            .forEach(/*dostuff*/);

}


private void printVerbose(String v) {
    if(verbose) {
        System.out.println(v);
    }

}

like image 899
shellfishMonkey Avatar asked Jan 02 '23 17:01

shellfishMonkey


2 Answers

You could do something like this :

    Stream<Integer> stream = alist.stream();
    if(verbose) {
        stream = stream
                .peek(System.out::println);
    }
    stream.forEach(/*dostuff*/);
like image 116
Matthieu Gabin Avatar answered Jan 04 '23 06:01

Matthieu Gabin


There's another way that checks the flag only once, when creating the Consumer to be passed to peek. You need the following method:

public static <T> Consumer<? super T> logIfNeeded(boolean verbose) {
    return verbose ? System.out::println : t -> { };
}

Then, in your stream pipeline:

alist.stream()
        .peek(logIfNeeded(verbose))
        .forEach(/*dostuff*/);

The difference with your 2nd approach is that the flag is not checked for every element; the action is chosen eagerly, when the static method is called at stream pipeline declaration.

like image 24
fps Avatar answered Jan 04 '23 08:01

fps