1
votes

I am working in a project where I have two lists and need to map every single data on one list with the other list. Kind of a m * n mapping. How can we implement this code efficiently?

arr1[] = {"CAR", "TRUCK", "BUS"};
arr1[] = {"COLOR", "ENGINE"};

resulting array = {"CAR_COLOR", "CAR_ENGINE", "TRUCK_COLOR", "TRUCK_ENGINE", "BUS_COLOR", "BUS_ENGINE"}
1
The cartesian product of two lists (one of size n and one of size m) will always contain n*m elements. This is the best you can do, because each element has to be generated. Are you asking about methods to not need to hold all of the lists in memory? No solution is going to be faster than O(n*m).Welbog
Arrays.stream(arr1).flatMap(a -> Arrays.stream(arr2).map(b -> a + "_" + b)).toArray(String[]::new)shmosel

1 Answers

1
votes

Simple solution for your example

    String[] arr1 = {"CAR", "TRUCK", "BUS"};
    String[] arr2 = {"COLOR", "ENGINE"};

    List<String> list = new ArrayList();
    for (String s1 : arr1) {
        for (String s2 : arr2) {
            list.add(s1+"_"+s2);
        }
    }
    String[] result = list.toArray(new String[0]);