Finding an odd number from 2 dimensional integer array using Stream

Viewed 312

I am trying the code as follows

int[][] mat = new int[][]{new int[]{2,4,6}, new int[]{8,9,12}};
int oddInAll = Arrays.stream(mat).filter(i -> i%2 != 0).findFirst().getAsInt();

But this gives me the error

| Error: | bad operand types for binary operator '%' | first type: int[] | second type: int | int oddInAll = Arrays.stream(mat).filter(i -> i%2 != 0).findFirst().getAsInt(); |
^---^

| Error: | cannot find symbol | symbol: method getAsInt() |
int oddInAll = Arrays.stream(mat).filter(i -> i%2 != 0).findFirst().getAsInt(); |
^-------------------------------------------------------------^

What did I miss this time?

2 Answers

Well, Arrays.Stream in this case would result in your i to be of type int[] which can not be used in filter.

I would suggest using a similar example I'd shared previously for this operation as well.

int oddOrMin = Stream.of(arr) // Stream<int[]> and not integers
                     .flatMapToInt(Arrays::stream) // IntStream
                     .filter(i -> i % 2 != 0)
                     .findFirst() // OptionalInt
                     .orElse(Integer.MIN_VALUE); //default to some value

Similarity

The syntax of iterating over the one-dimensional and two-dimensional array remains same in the above solution.

Difference

The solution that I'd shared for one-dimensional array makes use of Stream.of(T t) where T is int[] as provided in the input. On the other hand, the solution suggested for two-dimensional array makes use of the Stream.of(T... values) where again the int[][] is considered to be int[]... and hence T evaluates to int[] to finally create a Stream<int[]>.

Use a flatMapToInt instead :

int oddInAll = Arrays.stream(mat).flatMapToInt(Arrays::stream)
                     .filter(i -> (i % 2 != 0)).findFirst().getAsInt();
Related