从二维数组或矩阵中移除重复项

huangapple go评论74阅读模式
英文:

Remove Duplicate from 2D array or Matrix

问题

我有以下的2D数组

5.0 5.0 100 99
5.5 5.5 101 100
6.0 6.0 102 101

我想要以下的期望输出

5.0 100 99
5.5 101 100
6.0 102 101

我尝试过,我已经将1D数组传递给了自定义函数,该函数将1D转换为2D数组,最终输出是 finalArr,我随后将其传递给 stream 函数,并映射为列表,然后查找不同之处

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

输出:

5.0  5.0    100
5.5  5.5    101
6.0  6.0    102

经过一些尝试,我设法得到了

5.0 100 99
5.5 101 100
6.0 102 101

通过以下代码:

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

现在我想将其收集为2D数组,是否有更好的方法?请提供建议。

英文:

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.

答案1

得分: 4

你必须对每个数组使用distinct(),可以使用以下方法解决你的问题:

String[][] result = Arrays.stream(finalArr)
        .map(s -> Arrays.stream(s).distinct().toArray(String[]::new))
        .toArray(String[][]::new);

输出

[[5.0, 100, 99], [5.5, 101, 100], [6.0, 102, 101]]
英文:

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

huangapple
  • 本文由 发表于 2020年10月11日 14:55:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64301388.html
匿名

发表评论

匿名网友

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

确定