Java 7 (Android) Sort Map By Value

August 17, 2017
Map<String, Integer> findCountry = new HashMap<>();
findCountry.put("Japan", 100);
findCountry.put("Taiwan", 50);
findCountry.put("Singapore", 10);
findCountry.put("China", 500);

List<Map.Entry<String, Integer>> sortedList = new LinkedList<>(findCountry.entrySet());
Collections.sort(sortedList, new Comparator<Map.Entry<String, Integer>>() {
    @Override
    public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
        // asc
        return (e1.getValue()).compareTo(e2.getValue());
        // desc
        // return (e2.getValue()).compareTo(e1.getValue());
    }
});

// need LinkedHashMap to maintain order
findCountry = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : sortedList) {
    Log.d(TAG, entry.getKey() + "=" + entry.getValue());
    findCountry.put(entry.getKey(), entry.getValue());
}

for (Map.Entry<String, Integer> entry : findCountry.entrySet()) {
    Log.d(TAG, entry.getKey() + "=" + entry.getValue());
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.