Search code examples
javaobjecthashmap

Getting min value from a hashmap which stores a object as value


I want to get the min value from the data in the HashMap for a certain value in a object and if possible without doing a for loop etc. To get that I have currently this:

HashMap<String, Country> biggestCountries = new HashMap<String, Country>();

As the HashMap. The data I want to compare is stored within the object country and is getable with:

country.getArea();

Untill now I have tried this to get the min value but I only got it to work when I replaced the object Country with a Integer:

Collections.min(biggestCountries.entrySet(), Map.Entry.comparingByValue()).getKey();

Does someone maybe know a good way to get this to work?


Solution

  • You can create a Comparator that sorts based on area and get the Entry from Map

    Comparator<Map.Entry<String, Country>> comp = 
             Comparator.comparing((Entry<String, Country> entry)->entry.getValue().getArea());
    

    Using Collections.min

    Collections.min(biggestCountries.entrySet(),comp);
    

    Using stream

    Entry<String, Country> entry = biggestCountries.entrySet()
                                                   .stream()
                                                   .min(comp)
                                                   .orElse(null);
    

    If you want to get only the Country, using stream

    Country minCountry = biggestCountries.values()
                            .stream()
                            .min(Comparator.comparing(Country::getArea))
                            .orElse(null);
    

    or using Collections.min

    Country minCountry = Collections.min(biggestCountries.values(),
                               Comparator.comparing(Country::getArea));