pierbin24
pierbin24

Reputation: 31

Java Element-wise merge of two list

I have two List<Int> of int like {1,2,3} and {4,5,6}.

I need to obtain a List<List<Int>> like: ((1,4),(2,5),(3,6))

How should i proceed? I tried with for but i can get only the cartesian product

Upvotes: 2

Views: 389

Answers (3)

WJS
WJS

Reputation: 40034

List<Integer> list1 = List.of(1,2,3);
List<Integer> list2 = List.of(4,5,6);
List<List<Integer>> merged = mergeLists(list1, list2);
System.out.println(merged); 

Prints

[[1, 4], [2, 5], [3, 6]]

This method accepts lists of any type <T> as long as they contain the same types and are the same length.

  • throw an exception if different lengths.
  • allocate a return ArrayList
  • initialize an index to 0
  • Using an enhanced for loop, iterate over one list and index the other
  • add a new list via List.of() to the return list. Since List.of() is immutable it is passed as an argument to new ArrayList<>()
  • return the result wnen the loop is finished.
public static <T> List<List<T>> mergeLists(List<T> list1,
        List<T> list2) {
    if (list1.size() != list2.size()) {
        throw new IllegalArgumentException("Lists must be the same size");
    }
    List<List<T>> list = new ArrayList<>();
    int i = 0;
    for (T v1 : list1) {
        list.add(new ArrayList<>(List.of(v1, list2.get(i++))));
    }
    return list;
}

Upvotes: 1

pierbin24
pierbin24

Reputation: 31

Ok I solved the problem like this:

public List<List<V>> Lister (List<V> list1, List<V> list2){
    List<List<V>> result = new ArrayList<>();
    if (list1.size() == list2.size()) {
      for(int i =0; i<list1.size(); i++){
        List<V> tempList = new ArrayList<>();
        tempList.add(list1.get(i));
        tempList.add(list2.get(i));
        result.add(tempList);
      }
    }
    return result;
  }

Upvotes: 0

rzwitserloot
rzwitserloot

Reputation: 102822

The key number here is 3: You want to loop 3 times. Each loop, you know what to do: Fetch the Xth number from input1, the Xth number from input2, put them together in a size-2 list, and that then forms the Xth entry in your output.

int[] in1 = ...;
int[] in2 = ...;
int[][] out;

assert input1.length == input2.length;
int len = input1.length;
out = new int[len][];
for (int i = 0; i < len; i++) {
  out[i] = new int[] {input1[i], input2[i]};
}

Upvotes: 1

Related Questions