Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort the Object's value inside the Hashmap<String, Object>

I want to sort an Hashmap by the object's value. In this case, by country code.

  KEY              OBJECT                        
  String        LoyaltyCountry
                     - country name
                     - country code
                     - country loc

My code is as follows:

public static HashMap<String, LoyaltyCountry> loyaltyCountrySortMap(HashMap<String, LoyaltyCountry> loyaltyCountryMap) {

            if (loyaltyCountryMap != null) {
                List keys = new ArrayList();
                keys.addAll(loyaltyCountryMap.keySet());
                Collections.sort(keys, new Comparator<LoyaltyCountry>() {
                    public int compare(LoyaltyCountry o1, LoyaltyCountry o2) {
                        return o1.getCountryName().compareTo(o2.getCountryName());
                    }
                });
            }

            return loyaltyCountryMap;
        }

How can I do this correctly?

like image 904
newbie Avatar asked Apr 12 '26 06:04

newbie


1 Answers

Here is a method that returns a Set containing the Map.Entry items sorted by their value.

public static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> entriesSortedByValues(Map<K, V> map) {
    SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(
            new Comparator<Map.Entry<K, V>>() {
                @Override
                public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
                    return e1.getValue().compareTo(e2.getValue());
                }
            });
    sortedEntries.addAll(map.entrySet());
    return sortedEntries;
}
like image 121
Sarel Botha Avatar answered Apr 14 '26 18:04

Sarel Botha



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!