Collecting a collection of list based on similar index

  • A+
Category:Languages

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

 


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()); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: