Reputation: 83
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
Reputation: 274423
You should box the IntStream
to a Stream<Integer>
, as Collector
s 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
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