Issue
Create a method uniqueValue that return a 2d integer array collection. The method accepts a 2d integer array for the purpose of returning unique collection in ascending order for each dimensions...
Example:
input:
int [][] myArray = {
{ 5, 32, 8, 45, 9, 10, 1, 2, 45, 6, 1, 8 },
{ 4, 2, 3, 1, 7, 3, 2, 6, 2, 2 }
};
output:
int[][] newArray = {
{ 1, 2, 5, 6, 8, 9, 10, 32, 45 },
{1, 2, 3, 4, 6, 7}
};
Solution
The solution below uses 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
}
Test:
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);
Output:
[1, 2, 5, 6, 8, 9, 10, 32, 45]
[1, 2, 3, 4, 6, 7]
Answered By - Alex Rudenko
Answer Checked By - Marie Seifert (JavaFixing Admin)