Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 iterate over all keys and find those keys which have multiple values. Please help me how can i do that?

like image 847
user967491 Avatar asked Feb 28 '26 12:02

user967491


1 Answers

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.

like image 54
Mark Peters Avatar answered Mar 03 '26 04:03

Mark Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!