3

I have created a hash multi map of following type: key as a pair of string, string and value as long.

HashMultimap<Pair<String, String>, Long> hm = HashMultimap.create();

I have inserted some values in the table using put function.

Now I want to find all those keys which have multiple values. I want to use for loop to iterate over all keys and find those keys which have multiple values. Please help me how can i do that?

Thomas Jung
  • 32,428
  • 9
  • 84
  • 114
user967491
  • 121
  • 1
  • 7

3 Answers3

4

Matt has the procedural way covered. The more functional approach (still verbose since Java doesn't have closures yet) would be something like this:

public class MoreThanOnePredicate<T extends Map.Entry<?, ? extends Collection<?>>> implements Predicate<T> {
    public boolean apply(T entry) {
       return entry.getValue().size() > 1;
    }
}

//...
return Maps.filterEntries(hm.asMap(), new MoreThanOnePredicate<Pair<String, String>, Collection<Long>>()).keySet();

I don't have the library and a compiler in front of me so there are probably some unresolved generics problems with that.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
2
Set<Pair<String, String>> keysWithMultipleValues = Sets.newHashSet();

for (Pair<String, String> key : hm.keySet())
{
    if (hm.get(key).size() > 1)
    {
        keysWithMultipleValues.add(key);
    }
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 1
    +1, though I think you want `&& values.size() > 1`. Also the spec says you don't need to check for null; if there is no mapping an empty collection will be returned. – Mark Peters Sep 27 '11 at 16:32
  • @Mark you're right - already corrected. Also noted that `Multimap#get()` never returns `null` – Matt Ball Sep 27 '11 at 16:33
2

This should be a bit more efficient than Matt's version as no lookup by keys is used:

Set<Pair<String, String>> r = Sets.newHashSet();
for(Entry<Pair<String, String>> e : create.keys().entrySet()) {
   if(e.getCount() > 1) r.add(e.getElement());
}
Thomas Jung
  • 32,428
  • 9
  • 84
  • 114