按值按字母顺序排序HashMap

Chi*_*ins 7 java sorting collections

我有一个HashMap<Object, Student>对象是学生的ID,而学生是学生的对象.

我如何通过学生名称来求助HashMap student->getName()

SLa*_*aks 15

HashMaps本质上是无序的,无法排序.

相反,您可以使用SortedMap实现,例如TreeMap.
但是,即使是已排序的地图也只能按其键排序.

如果要按值排序,则需要将它们复制到排序列表中.


Ste*_*HHH 5

您可能无法对 HashMap 进行排序,但您当然可以做一些提供相同效果的事情。我能够通过使用Javarevisited博客上发布的优秀代码对 Integer 的值进行降序对我的 HashMap <String, Integer> 进行排序。同样的原则也适用于 HashMap <String, String> 对象:

/*
 * Java method to sort Map in Java by value e.g. HashMap or Hashtable
 * throw NullPointerException if Map contains null values
 * It also sort values even if they are duplicates
 */
public static <K extends Comparable,V extends Comparable> Map<K,V> sortByValues(Map<K,V> map){
    List<Map.Entry<K,V>> entries = new LinkedList<Map.Entry<K,V>>(map.entrySet());

    Collections.sort(entries, new Comparator<Map.Entry<K,V>>() {

        @Override
        public int compare(Entry<K, V> o1, Entry<K, V> o2) {
            return o1.getValue().compareTo(o2.getValue());
            // to compare alphabetically case insensitive return this instead
            // o1.getValue().toString().compareToIgnoreCase(o2.getValue().toString()); 
        }
    });

    //LinkedHashMap will keep the keys in the order they are inserted
    //which is currently sorted on natural ordering
    Map<K,V> sortedMap = new LinkedHashMap<K,V>();

    for(Map.Entry<K,V> entry: entries){
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}
Run Code Online (Sandbox Code Playgroud)

要调用此方法,我使用:

Map<String, Integer> sorted = sortByValues(myOriginalHashMapObject);
Run Code Online (Sandbox Code Playgroud)

阅读更多:http : //javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html#ixzz2akXStsGj