Reputation: 540
I'm using a Multimap that has two values per key. Below is the code I'm using to get each value separately:
The first bit of code gets the first object value:
for(Object object : map.get(object))
{
return object
}
Then, I'm using another method to retrieve the other value. This method takes the first object as an argument:
for(Object object : team.get(object))
{
if(object != initialObject)
{
return object;
}
}
This seems like a 'hackish' way of doing things, so is there any way for me to get the values more easily?
Upvotes: 2
Views: 9488
Reputation: 1990
for getting all the values for the same key the most easiest way to do it will be :
Iterator iterator = multimap.get(key).iterator();
System.out.println("first element: " + iterator.next());
System.out.println("second element: " + iterator.next());
System.out.println("third element: " + iterator.next());
And so on
another option if you want to get all the elements without know how much elements there
Iterator iterator = multimap.get(key).iterator();
int index=1;
while (iterator.hasNext()) {
System.out.println(index +" element: " + iterator.next());
index++;
}
Upvotes: 0
Reputation: 18964
If you're using Guava, Iterables#get
is probably what you want - it returns the Nth item from any iterable, example:
Multimap<String, String> myMultimap = ArrayListMultimap.create();
// and to return value from position:
return Iterables.get(myMultimap.get(key), position);
If you're using a ListMultimap
then it behaves very much like a map to a List so you can directly call get(n)
.
Upvotes: 7
Reputation: 5552
Collection<Object> values = map.get(key);
checkState(values.size() == 2, String.format("Found %d values for key %s", values.size(), key));
return values.iterator().next(); // to get the first
Iterator<Object> it = values.iterator();
it.next(); // move the pointer to the second object
return it.next(); // get the second object
Upvotes: 3