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
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With