1

I have a query which returns List of Object[2]. I would like to convert this into a MultiMap which would contain Object[0] as key and Object[1] as value.

input list contains:

<id1, value1>
<id1, value2>
<id1, value3>
<id2, value1>
<id2, value2>
<id3, value2>

So when I do Collection coll = (Collection) multimap.get(id1);

col1 Should give --> value1,value2,value3

I can achive this looping through the list and putting it to the multimap, I would like to avoid that as my List is huge.

Thanks in advance!

9
  • Which Multimap are you using? Apache? Guava? Commented Nov 13, 2013 at 22:12
  • 1
    not really anyway around looping that i can see. At most you'll find some library that loops for you. Commented Nov 13, 2013 at 22:16
  • 1
    "I would like to avoid that as my List is huge." This doesn't make sense - you can't punt all items from collection A to collection B without iterating over collection A. Commented Nov 13, 2013 at 22:18
  • 1
    You will have to loop through it. Also, measure before making assumptions. 'Huge' is quite relative and the time spent in putting the values in the multimap might be a few nano seconds only... Commented Nov 13, 2013 at 22:19
  • 1
    Addendum: if you use the MultiHashMap remember to preinitialize the multimap with the number of expected values in order to avoid unnecessary rehashing. Commented Nov 13, 2013 at 22:21

1 Answer 1

2
for(Object obj[] : list ){
    multimap.put(obj[0], obj[1]);
}

Assuming youre using apache multimap

Sign up to request clarification or add additional context in comments.

5 Comments

I would like to use something where I don't have to loop through.
@Gayathri No such thing exists.
A matter of style, but I find clearer for begginers Object[] obj rather than Object obj[]
@Darkhogg Clearer for anyone really. The latter is a C artefact, the former notation makes more sense given Java's type model.
Sorry, im more used to C Conventions and it shows in my java code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.