Java sorting and HashMap

不想你离开。 提交于 2019-12-12 04:06:37

问题


I have a HashMap<String, Integer> How can I sort this data structure and keep the key-value mappings? I want to sort by VALUES not keys.

Collection<Integer> counts = tableFrequency.values();

But then I lose the key mappings. Or is there a better associative data-structure that I could have used instead of the HashMap?


回答1:


To sort a Map by its values, you could grab its entrySet and sort that with a custom Comparator.

List<Entry<K,V>> sorted = new ArrayList<>(map.entrySet());
Collections.sort(sorted, new Comparator<Entry<K,V>>() {
    public int compare(Entry<K,V> o1, Entry<K,V> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
};



回答2:


TreeMap keeps the elements in the order in wich you added them. It seems like a perfect answer for you.

Beware though, some actions will be way slower than with a HashMap, things such as searching...




回答3:


The class TreeMap is what you want:

TreeMap treeMap = new TreeMap();

treeMap.put("One", new Integer(1));
treeMap.put("Two", new Integer(2));

Object obj = treeMap.get("Two");
System.out.println(obj);

It uses the compare() method to be able to sort elements.

Since your new question is about sorting by values, this is a duplicate of this post



来源:https://stackoverflow.com/questions/10167278/java-sorting-and-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!