Finding an odd number from 2 dimensional integer array using Stream

  • A+

I am trying the code as follows

int[][] mat = new int[][]{new int[]{2,4,6}, new int[]{8,9,12}}; int oddInAll = -> 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 = -> i%2 != 0).findFirst().getAsInt(); |

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

What did I miss this time?


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 


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


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[]>.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: