Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the maximum Set size from a HashMap

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.

like image 349
xmen-5 Avatar asked Mar 06 '26 12:03

xmen-5


2 Answers

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));
like image 60
Ousmane D. Avatar answered Mar 09 '26 02:03

Ousmane D.


we should get 3 as the maximum size set.

To get the maximum size of a Set within the map you can use:

int maxSetSize = adj.values()
        .stream()
        .max(Comparator.comparingInt(Set::size))
        .map(Set::size)
        .orElse(0);
like image 44
Naman Avatar answered Mar 09 '26 02:03

Naman



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!