Java排序和HashMap [英] Java sorting and HashMap

查看:210
本文介绍了Java排序和HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();

但是我失去了关键的映射。还是有一个更好的关联数据结构,我可以使用而不是HashMap?

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

推荐答案

排序映射通过其值,您可以获取其 entrySet ,并使用自定义 比较器

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());
    }
};

这篇关于Java排序和HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆