get the maximum Set size from a HashMap

zak zak :

I have a hashMap of <Integer, Set<Integer>>.

I'm willing to get the Set that have the maximum size using java stream operation.

Here is my example:

public class Example {

     public static void main( String[] args ) {
         Map<Integer,Set<Integer>> adj = new HashMap<>();
         Set<Integer> set1 = Stream.of(1,2,3).collect(Collectors.toSet());
         Set<Integer> set2 = Stream.of(1,2).collect(Collectors.toSet());
         adj.put(1,set1);
         adj.put(2,set2);
     }
}

I have tried this:

 Collections.max(adj,Comparator.comparingInt(Set::size));

but I'm getting a compilation error because the size() method in the Set interface is not static.

Normally we should get 3 as the maximum size set.

Ousmane D. :

You cannot use a Map<Integer,Set<Integer>> with Collection.max. as it's defined as taking a Collection.

public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)

So, to make it work, either do:

Collections.max(adj.values(), Comparator.comparingInt(Set::size));

or a stream:

adj.values()
   .stream()
   .max(Comparator.comparingInt(Set::size));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88409&siteId=1