Home > Blockchain >  How to find number of unique elements in a 2D array in java? Is there any method present there?
How to find number of unique elements in a 2D array in java? Is there any method present there?

Time:04-21

I want to calculate no. of distinct elements (char datatype) in a 2D array in java. When I tried Arrays.stream(arr).distinct().count() it gave wrong ans and seems like it is also taking some garbage value as it is returning 3 when the ans was 2, here is a screenshot of that.Here is the photo, when I debugged my code, it seems like it is only checking for the 1st row for distinct values but that too in wrong way

Is there any method to find no of distinct elements in a 2D array.

CodePudding user response:

The problem is not the stream is the array, you used 2D array so when you stream it you get a 1D array. So you need to use flatMap on the stream to create a stream of your basic type.

CodePudding user response:

If arr is a 2D array, eg String[][] arr = {{"1", "2"}, {"2", "4"}, {"3", "4"}}

Then Arrays.stream(arr) is giving you a Stream<String[]> where each item in the stream is a 1 dimensional array of Strings.

If you want to distinguish between the actual elements in the 2D array then you also need to flatMap each String[] in your initial stream. Like this: Arrays.stream(arr).flatMap(Arrays::stream) which will return a Stream<String> of all elements in each of the subarrays for which you find the number of distinct values with Arrays.stream(arr).flatMap(Arrays::stream).distinct().count()

  • Related