I have an attribute this.sudoku
which is a int[9][9]
array.
I need to get a column of this into a set.
Set<Integer> sudoku_column = IntStream.range(0, 9)
.map(i -> this.sudoku[i][column])
.collect(Collectors.toSet());
I expect a columns values in this set. but it says that Collectors.toSet()
cannot be applied to this collect function in the chain. Can someone explain why?
IntStream#map
consumes an IntUnaryOperator
which represents an operation on a single int-valued operand that produces an int-valued result thus the result is an IntStream
, however IntStream
does not have the collect
overload you're attempt to use, which means you have a couple of options; i.e. either use IntStream#collect
:
IntStream.range(0, 9)
.collect(HashSet::new, (c, i) -> c.add(sudoku[i][column]), HashSet::addAll);
or use mapToObj
to transform from IntStream
to Stream<Integer>
which you can then call .collect(Collectors.toSet())
upon.
IntStream.range(0, 9)
.mapToObj(i -> this.sudoku[i][column])
.collect(Collectors.toSet());
IntStream#map
takes an IntUnaryOperator
which is a function to transform an int
to another int
.
It's fine if you want to continue with an IntStream
. But if you need to collect the stream into a Set<Integer>
, you need to turn your IntStream
into a stream of boxed int
s, a Stream<Integer>
, by IntStream#boxed
.
.map(i -> this.sudoku[i][column])
.boxed()
.collect(Collectors.toSet());
Collectors.toSet()
cannot be applied to thiscollect
function in the chain
Collectors.toSet()
return a Collector
which doesn't fit the signature of the single collect(Supplier, ObjIntConsumer, BiConsumer)
method in IntStream
. Though, it's suitable for Stream.collect(Collector)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With