创建一个返回2d整数数组集合的方法uniqueValue。该方法接受一个2d整数数组,以便按升序返回每个维度的唯一集合。。。
示例:
输入:
int [][] myArray = {
{ 5, 32, 8, 45, 9, 10, 1, 2, 45, 6, 1, 8 },
{ 4, 2, 3, 1, 7, 3, 2, 6, 2, 2 }
};
输出:
int[][] newArray = {
{ 1, 2, 5, 6, 8, 9, 10, 32, 45 },
{1, 2, 3, 4, 6, 7}
};
下面的解决方案使用Java Stream API:
static int[][] sortAndRemoveDuplicates(int[][] arr) {
return Arrays.stream(arr) // Stream of int[]
.map(row -> // process each row
IntStream.range(0, row.length) // analog of for loop, stream of indexes
.map(i -> row[i]) // convert to stream of int elements
.sorted() // sort in ascending order by default
.distinct() // remove duplicates
.toArray() // build int[] array
)
.toArray(int[][]::new); // build result 2D array
}
测试:
int[][] myArray = {
{5, 32, 8, 45, 9,10 ,1 ,2 , 45, 6, 1, 8},
{4, 2, 3, 1, 7, 3, 2, 6, 2, 2}
};
int[][] newArray = sortAndRemoveDuplicates(myArray);
Arrays.stream(newArray)
.map(Arrays::toString)
.forEach(System.out::println);
输出:
[1, 2, 5, 6, 8, 9, 10, 32, 45]
[1, 2, 3, 4, 6, 7]
java提供了一个名为Arrays
的类,它为您提供了很多选项,例如我用来对数组进行排序,然后删除重复的:
int[][] myArray = { { 5, 32, 8, 45, 9, 10, 1, 2, 45, 6, 1, 8 }, { 4, 2, 3, 1, 7, 3, 2, 6, 2, 2 } };
for (int i = 0; i < myArray.length; i++) {
Arrays.sort(myArray[i]);
myArray[i] = Arrays.stream(myArray[i]).distinct().toArray();
}
for (int i = 0; i < myArray.length; i++) {
System.out.println(Arrays.toString(myArray[i]));
}