Search code examples
javaintellij-ideajava-stream

"Refactor code so that stream pipeline is used" when assigning stream to a variable before passing to method


I have the following method:

public int parseIntStream(Stream<Integer> stream) {
    return stream.reduce(0, Integer::sum);
}

When I try to pass a stream like so, IntelliJ gives me the warning Refactor code so that stream pipeline is used:

Stream<int> intStream = Stream.of("a","b","c").map(letter -> letter.equals("a") ? 1 : (letter.equals("b") ? 2 : (letter.equals("c") ? 3 : 0)));
int x = parseIntStream(intStream);

However, if I don't assign the first stream to a variable, the warning goes away:

int x = parseIntStream(Stream.of("a","b","c").map(letter -> letter.equals("a") ? 1 : (letter.equals("b") ? 2 : (letter.equals("c") ? 3 : 0))));

I know map is an intermediate operation, but I'm not trying to terminate the stream until I pass it to the method. I'm not even using the stream until then. I am only assigning it at the beginning for the sake of readability.


Solution

  • You have some type mismatches which javac and the IDE are trying to accommodate. Use mapToInt rather than map to produce an IntStream. The IntStream has its own sum method so you don't have to write one.

    int sum = Stream.of("a","b","c").mapToInt( <your-map-function> ).sum();