Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 398
bell_pepper Avatar asked Jan 26 '23 21:01

bell_pepper


2 Answers

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());
like image 103
Ousmane D. Avatar answered Jan 29 '23 12:01

Ousmane D.


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).

like image 31
Andrew Tobilko Avatar answered Jan 29 '23 11:01

Andrew Tobilko