collecting column of multidimensional array to set

bell_pepper :

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?

Ousmane D. :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73485&siteId=1