有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是使用值对地图进行排序的最佳方法

private Map<Character, Integer> frequencies;

我有一个Map,其中Character是键,其关联的Integer是值

按价值排序的最佳/最快/有效方式是什么

也就是说,地图可能有
a、 1
c、 10
p、 5
s、 7
分类之后, 这将是
a、 1
p、 5
s、 7
c、 十

我想用优先级队列和整数来做,但如果整数VAL是重复的,我会丢失字符值


共 (2) 个答案

  1. # 1 楼答案

    优先级队列是一种不错的方法——只需从映射中get the ^{} set,并重写Comparator作为队列的输入

    Map<Character,Integer> map = new HashMap<Character, Integer>();
    map.put('a',1);
    map.put('c',10);
    map.put('p',5);
    map.put('2',7);
    PriorityQueue<Entry<Character, Integer>> pq = new PriorityQueue<Map.Entry<Character,Integer>>(map.size(), new Comparator<Entry<Character, Integer>>() {
    
        @Override
        public int compare(Entry<Character, Integer> arg0,
                Entry<Character, Integer> arg1) {
            return arg0.getValue().compareTo(arg1.getValue());
        }
    });
    pq.addAll(map.entrySet());
    while (!pq.isEmpty()) {
        System.out.println(pq.poll());
    }
    

    将产生(如预期的那样):

    a=1
    p=5
    2=7
    c=10
    

    注意:避免使用带有键的SetMap作为映射的值,因为它无法很好地处理重复的值

  2. # 2 楼答案

    使用谷歌番石榴。它包含可以反转的BiMap实现,然后仅对反转的映射键进行排序

    Map<Character, Integer> myMap = HashBiMap.create();
    // put your values in myMap
    Map<Integer, Character> inversed = myMap.inverse();
    SortedMap<Integer, Character> sortedInversed = new TreeMap<Integer, Character>(inversed);
    

    因此,只需重复已排序的数据即可