Java排序和HashMap

Cod*_*lus 0 java sorting hashmap data-structures

我有一个HashMap<String, Integer>如何对这个数据结构进行排序并保持键值映射?我想按VALUES排序而不是键.

Collection<Integer> counts = tableFrequency.values();
Run Code Online (Sandbox Code Playgroud)

但后来我丢失了关键映射.或者是否有一个更好的关联数据结构,我可以使用而不是HashMap?

Jef*_*rey 6

Map按其值排序,您可以抓取它entrySet并使用自定义对其进行排序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());
    }
};
Run Code Online (Sandbox Code Playgroud)