Adam Amin
Adam Amin

Reputation: 1456

How to extract lists from a list of lists

I have the following list of lists:

    List<List<Integer>> fronts = new ArrayList<>();
    List<Integer> f0 = new ArrayList<>();
    f0.add(0);
    f0.add(1);
    f0.add(2);
    f0.add(3);
    fronts.add(f0);

    List<Integer> f1 = new ArrayList<>();
    f1.add(6);
    f1.add(7);
    f1.add(8);
    f1.add(9);
    fronts.add(f1);

    List<Integer> f2 = new ArrayList<>();
    f2.add(10);
    f2.add(11);
    f2.add(12);
    f2.add(13);
    fronts.add(f2);

I would like to get four lists where the first list contains the first element of each list such that 0,6,10 and the second list is 1,7,11 and so on.

How can I do that?

Upvotes: 1

Views: 148

Answers (2)

Boney
Boney

Reputation: 1780

You can try this way:

for(int i=0; i<fronts.get(0).size();i++){
    List<Integer> newList = new ArrayList<Integer>();
    for(int j=0; j<fronts.size();j++){
        newList.add(fronts.get(j).get(i));
    }
    System.out.println(newList);
}

Upvotes: 1

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

You can create a list containing the required 4 lists.

Do it as follows:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<List<Integer>> fronts = new ArrayList<List<Integer>>();
        List<Integer> f0 = new ArrayList<>();
        f0.add(0);
        f0.add(1);
        f0.add(2);
        f0.add(3);
        fronts.add(f0);

        List<Integer> f1 = new ArrayList<>();
        f1.add(6);
        f1.add(7);
        f1.add(8);
        f1.add(9);
        fronts.add(f1);

        List<Integer> f2 = new ArrayList<>();
        f2.add(10);
        f2.add(11);
        f2.add(12);
        f2.add(13);
        fronts.add(f2);

        List<List<Integer>> result = new ArrayList<List<Integer>>();
        for (int i = 0; i < fronts.get(0).size(); i++) {
            List<Integer> temp = new ArrayList<Integer>();
            for (int j = 0; j < fronts.size(); j++) {
                temp.add(fronts.get(j).get(i));
            }
            result.add(temp);
        }
        System.out.println(result);
    }
}

Output:

[[0, 6, 10], [1, 7, 11], [2, 8, 12], [3, 9, 13]]

Upvotes: 1

Related Questions