Reputation: 579
I have 2D array below
5.0 5.0 100 99
5.5 5.5 101 100
6.0 6.0 102 101
I want the expected output below
5.0 100 99
5.5 101 100
6.0 102 101
What I'd tried, I have passed the 1D array to my custom function which will convert 1d to 2D array, the final output is finalArr
, which I further pass to stream
function and map as list and find the ditinct
String finalArr[][] = convert1DTo2DArray(arr3, 3, 4);
Arrays.stream(finalArr)
.map(Arrays::asList)
.distinct()
.forEach(row -> System.out.printf("%-3s%-7s%s\n", row.get(0), row.get(1), row.get(2)));
Output:
5.05.0 100
5.55.5 101
6.06.0 102
After some workaround, I've managed to get
5.0 100 99
5.5 101 100
6.0 102 101
by this code :
Arrays.stream(finalArr)
.map(Arrays::asList)
.distinct()
.forEach(row -> System.out.printf("%-5s%-7s%s\n", row.get(1), row.get(2), row.get(3)));
Now I want to collect it as 2D array, is there any better approach for the same, kindly suggest.
Upvotes: 2
Views: 368
Reputation: 59988
You have to use distinct()
for each array, you can solve your problem using :
String[][] result = Arrays.stream(finalArr)
.map(s -> Arrays.stream(s).distinct().toArray(String[]::new))
.toArray(String[][]::new);
Outputs
[[5.0, 100, 99], [5.5, 101, 100], [6.0, 102, 101]]
Upvotes: 4