Retrieving specific values in Multimap

后端 未结 2 1221
悲哀的现实
悲哀的现实 2021-01-22 16:45

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:

相关标签:
2条回答
  • 2021-01-22 17:33
    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
    
    0 讨论(0)
  • 2021-01-22 17:48

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

    0 讨论(0)
提交回复
热议问题