Filtering Guava HashMultimap keys by count
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 iter开发者_开发问答ate over all keys and find those keys which have multiple values. Please help me how can i do that?
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.
Set<Pair<String, String>> keysWithMultipleValues = Sets.newHashSet();
for (Pair<String, String> key : hm.keySet())
{
if (hm.get(key).size() > 1)
{
keysWithMultipleValues.add(key);
}
}
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());
}
精彩评论