简体   繁体   中英

How to combine two List<Object[]> objects into a single List<Object[]>

I have two List<Object[]> s.

The first one has elements like {1, 'a'}, {2, 'd'} , etc... That's the Object[] here is always an array of two Object s ( Integer and Character ).

The second one has {1, 12.0}, {2, 14.0} , etc.. The Object[] here is an array of two Object 's ( Integer and Double ).

Integer s from the first list are absolutely the same to the Integer s from the second List. I mean, for any list element e from the first list there is an element ee from the second list such that e[0] == ee[0] . And vice versa.

I need to construct a List<Object[]> from the two List<Object[]> s such that the List<Object[]> has to contain elements like {1, 'a', 12.0}, {2, 'd', 14.0} , etc...

How can I do that?

Maybe there's an instant solution from the apache commons or google guava libraries?

A tiny note : The lists are returned by the criteria.list() method in hibernate.

Something like this should work

Map<Integer, Character> map1 = new HashMap<Integer, Character>();
for (Object[] o : list1) {
    map1.put((Integer)o[0], (Character)o[1]);
}

Map<Integer, Double> map2 = new HashMap<Integer, Double>();
for (Object[] o : list2) {
    map2.put((Integer)o[0], (Double)o[1]);
}

List<Object[]> list3 = new ArrayList<Object[]>();
for (int i = 0; i < list1.size(); i++) {
    list3.add(new Object[] { i, map1.get(i), map2.get(i) })
}

In any solution, I would first create a map of the second list, and look that up while iterating over the first list.

In java 8, it's reasonably neat (2 lines):

final Map<Integer, Double> map = list2.stream().collect(Collectors.groupingBy(a -> a[0], a -> a[1]));
List<Object[]> result = list1.stream()
    .map(a -> new Object{a[0], a[1], map.get(a[0])})
    .collect(Collectors.toList());

Note: code not tested and no IDE used (thumbed on phone), so there could be errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM