Tom
Tom

Reputation: 83

How can I use streams to group elements by a remainder of division by the give divisor?

I hava an inputStream of Integers and some number as a devisor. I want to have a result like this:
sumByRemainder(3, (1,2,3,4,5)) -> (0, 3), (1, 5), (2, 7)

What's wrong with the code below?

public Map<Integer, Integer> sumByRemainder(Integer devisor, IntStream is) {
    Map<Integer, Integer> map = is.collect(Collectors.groupingBy(s -> s % devisor, 
Collectors.summingInt()));
    return map;
}

Upvotes: 2

Views: 966

Answers (2)

Sweeper
Sweeper

Reputation: 274423

You should box the IntStream to a Stream<Integer>, as Collectors only work with the wrapper types and not primitives.

public Map<Integer, Integer> sumByRemainder(int divisor, IntStream is) {
    return is.boxed().collect(Collectors.groupingBy(s -> s % divisor,
        Collectors.summingInt(x -> x)));
}

Upvotes: 3

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

Did you mean:

return is
       .boxed()
       .collect(Collectors.groupingBy(s -> s % devisor, Collectors.summingInt(x -> x)));

Note that you should to use .boxed() to get primitive value from the IntStream, instead the value in groupingBy is considered as Object and you can't devide Object by Integer

Upvotes: 1

Related Questions