How to extract lists from a list of lists

Adam Amin :

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?

Arvind Kumar Avinash :

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]]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=26863&siteId=1