St.Antario
St.Antario

Reputation: 27385

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 Objects (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).

Integers from the first list are absolutely the same to the Integers 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.

Upvotes: 1

Views: 1703

Answers (2)

Bohemian
Bohemian

Reputation: 425023

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.

Upvotes: 2

Predrag Maric
Predrag Maric

Reputation: 24423

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) })
}

Upvotes: 3

Related Questions