Reputation: 1906
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.
Upvotes: 3
Views: 157
Reputation: 31878
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);
Upvotes: 3
Reputation: 56423
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));
Upvotes: 4