Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collecting a collection of list based on similar index

I have a collection like : List<List<Object>> firstList

I want to group together a similar list of pattern : List<List<Object>> secondList but grouped by indexes.

say

firstList [1]:
   0 = {Object A}"
   1 = {Object B}"
   2 = {Object C}"

firstList [2]:
   0 = {Object A}"
   1 = {Object B}"
   2 = {Object C}"

I want to group this collection as

secondList [1]:
   0 = {Object A}"
   1 = {Object A}"

secondList [2]:
   0 = {Object B}"
   1 = {Object B}"

secondList [3]:
   0 = {Object C}"
   1 = {Object C}"

What I have tried so far is

for (int i = 0; i <firstList.size() ; i++) {
    List<Object> list = firstList.get(i);
    List<Object> rlPr = new ArrayList<>();

    for (int j = 0; j <list.size()-1; j++) {
        rlPr.add(list.get(i));
    }
    secondList.add(rlPr);
}

But I am not getting what is expected. I am using java 8.

EDIT : ALL THE LIST ARE OF SAME SIZES

like image 216
Einstein_AB Avatar asked Feb 12 '19 13:02

Einstein_AB


People also ask

Does list allow index based addition and retrieval of items?

List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to insert, update, delete and search the elements. It can have the duplicate elements also. We can also store the null elements in the list.

Which collection in Java is indexed?

An index can be defined on a Collection property (java. util. Collection implementation) or Array. Setting such an index means that each of the Collection's or Array's items is indexed.


1 Answers

You can use a Map to group the values by index:

Map<Integer, List<Object>> map = new TreeMap<>();
for (List<Object> objects : firstList) {
    for (int i = 0, l = objects.size(); i < l; i++) {
        map.computeIfAbsent(i, k -> new ArrayList<>()).add(objects.get(i));
    }
}

And then to get the List back:

List<List<Object>> secondList = new ArrayList<>(map.values());
like image 92
Lino Avatar answered Sep 23 '22 08:09

Lino