| Sort Map by value |
|
|
|
| Written by Charles | |||||
| Monday, 14 December 2009 18:07 | |||||
|
Sometimes we want to sort a Map by its values, as opposed to its keys. Occasionally this can be done by reversing the Map as in the example here, but more likely you need to sort a List of the entries. Why? Because values could be duplicated, in which case entries would be lost on reversal, since a Map can't contain duplicate keys. Here is a way of sorting, The code is HERE import java.util.*;
public class MapValueSort { public static void main(String[] args) { Map<String, String> m = new HashMap<String, String>(); m.put("zero", "0"); m.put("nil", "0"); m.put("one", "1"); List<Map.Entry<String, String>> entries = MapValueSort.sortByValue(m); System.out.println(entries); } @SuppressWarnings("unchecked") public static <K, V extends Comparable> List<Map.Entry<K, V>> sortByValue( Map<K, V> map) { List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(map.size()); entries.addAll(map.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) { return e1.getValue().compareTo(e2.getValue()); } }); return entries; } }
Only registered users can write comments!
Powered by !JoomlaComment 3.26
3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved." |
|||||
| Last Updated ( Monday, 14 December 2009 18:28 ) |



