Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java: Pairing values from 1D arrays to 2D arrays while excluding corresponding values

Given arr1: [0, 1, -1, 3, -1],

and arr2: [15, 15, 10, 20, 20],

how can I create this 2D array:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[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));
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading