bell_pepper
bell_pepper

Reputation: 187

collecting column of multidimensional array to set

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?

Upvotes: 4

Views: 128

Answers (2)

Andrew
Andrew

Reputation: 49606

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 ints, a Stream<Integer>, by IntStream#boxed.

.map(i -> this.sudoku[i][column])
.boxed()
.collect(Collectors.toSet());

Collectors.toSet() cannot be applied to this collect 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).

Upvotes: 4

Ousmane D.
Ousmane D.

Reputation: 56433

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());

Upvotes: 4

Related Questions