Search code examples
javalambdafunctional-programmingjava-stream

How to use an if statement in a Java stream to avoid a duplicate stream process


Here is my code from the Java MOOC.fi course where I am learning about streams. The code below works but the way I wrote it is quite amateur. I was thinking of somehow integrating an if statement in the stream with the condition of the answer given in an earlier input to predicate the process by changing one line (the filter method). Any ideas?

System.out.println("Print the average of the negative numbers or the positive numbers? (n/p)");
String answer = scanner.nextLine();
double average;

if (answer.equals("n")) {
    average = inputs.stream()
            .mapToInt(s -> Integer.valueOf(s))
            .filter(pos -> pos < 0)
            .average()
            .getAsDouble();
} else {
    average = inputs.stream()
            .mapToInt(s -> Integer.valueOf(s))
            .filter(pos -> pos > 0)
            .average()
            .getAsDouble();
}

I tried forEach but I did not understand how to use it. The collection I am giving to stream is an ArrayList.

I am on Java 11.


Solution

  • You could use a single stream containing a ternary expression in the filter() step which chooses which comparison against pos to use:

    average = inputs.stream()
                    .mapToInt(s -> Integer.valueOf(s))
                    .filter(pos -> "n".equals(answer) ? pos < 0 : pos > 0)
                    .average()
                    .getAsDouble();