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.
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));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With