user8616404
user8616404

Reputation:

Populate multiple lists from one list

How can I populate three arrayLists from one list in way value from index1 into lista1, value from index2 into lista2, value from index3 into lista3, value from index4 into lista1 and so on...?

ArrayList<String> lista = new ArrayList<String>();

        ArrayList<String> lista1 = new ArrayList<String>();
        ArrayList<String> lista2 = new ArrayList<String>();
        ArrayList<String> lista3 = new ArrayList<String>();

        sh.forEach(row -> {
                row.forEach(cell -> {
                String cellvalue = dataFormatter.formatCellValue(cell);
                lista.add(cellvalue);
            });
        });

Upvotes: 1

Views: 179

Answers (3)

Naghaveer R
Naghaveer R

Reputation: 2944

Java8+ stream API, you can try this

    List<String> lista = Arrays.asList("A","B","C","D","E");

    List<String> list1 = lista.stream()
            .filter(x -> lista.indexOf(x) % 3 == 0)
            .collect(Collectors.toList());

    List<String> list2 = lista.stream()
            .filter(x -> lista.indexOf(x) % 3 == 1)
            .collect(Collectors.toList());

    List<String> list3 = lista.stream()
            .filter(x -> lista.indexOf(x) % 3 == 2)
            .collect(Collectors.toList());

Upvotes: 1

Eslam Nawara
Eslam Nawara

Reputation: 765

You can add the three list in a three-element array and use a traditional for loop to iterate over them. Here's the modified code

    ArrayList<String> lista = new ArrayList<String>();
    ArrayList<String>[] lists = new ArrayList[3];

    lists[0] = new ArrayList<String>();
    lists[1] = new ArrayList<String>();
    lists[2] = new ArrayList<String>();


    for(int i = 0; i < lista.size(); i++){
        lists[i % lists.length].add(lista.get(i));
    }

Upvotes: 3

ArrayList<String> lista = new ArrayList<String>();

ArrayList<String> lista1 = new ArrayList<String>();
ArrayList<String> lista2 = new ArrayList<String>();
ArrayList<String> lista3 = new ArrayList<String>();

ArrayList<String>[] newLists = new ArrayList[]{lista1, lista2, lista3};
for (int i=0 ; i< lista.size(); i ++ ){
  newLists[i % 3].add(lista.get(i)); 
}

Upvotes: 4

Related Questions