Given arr1: [0, 1, -1, 3, -1],
and arr2: [15, 15, 10, 20, 20],
how can I create this 2D array:
[[0, 15], [1, 15], [3, 20]]
You’ll notice that I’m trying to exclude -1 values and their corresponding values in the same indices between both arrays.
I’m thinking create a copy of arr1 that excludes -1 values but I’m not sure how to go from there.
>Solution :
you can try:
public static void main(String[] args) {
int[] arr1 = new int[]{0, 1, -1, 3, -1};
int[] arr2 = new int[]{15, 15, 10, 20, 20};
long length1 = Arrays.stream(arr1).filter(i -> i != -1).count();
long length2 = Arrays.stream(arr2).filter(i -> i != -1).count();
int index = 0;
int resultLength = Math.toIntExact(Math.min(length1, length2));
int[][] result = new int[resultLength][2];
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != -1 && arr2[i] != -1) {
result[index][0] = arr1[i];
result[index][1] = arr2[i];
index ++;
}
}
// Result: [[0, 15], [1, 15], [3, 20]]
System.out.println(Arrays.deepToString(result));
}