简体   繁体   中英

How do I iterate through a HashMap<String, Set<String>> and return which Set<String> is the largest?

I am trying to figure out how to return the largest Set in the Hashmap. I know the basic way of doing it but I cant get it right.

I tried iterating over all the keys in the hashmap by doing the following code. I also just realized that by doing this code, I will only be able to return the size of the largest set not the actual set itself. Is there a much better way? I will greatly appreciate any help! Thank you!

Map<String, Set<String>> category = new Hashmap<String, Set<String>>();
int largest = //someInt;
for(String d : category.keySet()) {
    if (category.get(d).size() > //largest)
        largest = category.get(d).size();
} return largest;

While other answers have shown how you can fix your code, here is another way to do it in a single statement:

Set<String> largestSet = category.values().stream()
        .max(Comparator.comparingLong(Set::size))
        .orElse(null);

You can try this

Map<String, Set<String>> category = new Hashmap<String, Set<String>>();
int largest = 0;
Set<String> largeSet = new HashSet<String>();
for(String d : category.keySet()) {
    if (category.get(d).size() > largest)
        largest = category.get(d).size();
        largeSet = category.get(d);
}
return largeSet; 

You can just do so:

Map<String, Set<String>> category = new HashMap<>();
Set<String> set = new HashSet<>();
int largest = 0;
for(String d : category.keySet()) {
    if (category.get(d).size() > largest) {
        largest = category.get(d).size();
        set = category.get(d);
    }
}
return set;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM