how to merge 3 lists into a list like a table data in java

Viewed 23

Let suppose i have three different list of string type data which I fetched from a table (different Columns). Now I want to add these three lists like a table data in third list. Please suggest.

List<String> allData = new LinkedList<>();
List<String> list1 = new LinkedList<>();
List<String> list2 = new LinkedList<>();
List<String> list3 = new LinkedList<>();
    
list1.add("1");
list1.add("2");
        
list2.add("3");
list2.add("4");
        
list3.add("5");
list3.add("6");

2 Answers

Iterate over the same indice for each and collect in a new one

List<String> list1 = List.of("1", "2");
List<String> list2 = List.of("3", "4");
List<String> list3 = List.of("5", "6");
List<List<String>> allLists = List.of(list1, list2, list3);

List<List<String>> allData = new ArrayList<>();
for (int i = 0; i < list1.size(); i++) {
    List<String> tmp = new ArrayList<>();
    for (List<String> someList : allLists) {
        tmp.add(someList.get(i));
    }
    allData.add(tmp);
}

System.out.println(allData);
// [[1, 3, 5], [2, 4, 6]]

Assuming that all lists are of the same size, you can combine an arbitrary number of the lists joining elements under the same index that using Stream API.

For that, you can create a stream over the indices, and then for every index create a stream of list elements that correspond to that index.

Collect each nested stream into a list applying Java 16 toList() or collect(Collectors.toList()), and then collect all the list into a nested list.

Here's a generic implementation:

@SafeVarargs
public static <T> List<List<T>> joinAllByIndex(List<T>... lists) {
    if (lists.length == 0) return Collections.emptyList();
    
    return IntStream.range(0, lists[0].size())
        .mapToObj(i -> Arrays.stream(lists)
            .map(list -> list.get(i))
            .toList())
        .toList(); // for Java 16+ or collect(Collectors.toList()) for earlier versions
}
Related