【问题标题】:Java data structure that order objects according the occurance [duplicate]根据出现对对象进行排序的Java数据结构[重复]
【发布时间】:2017-08-16 19:28:55
【问题描述】:

是否有一个数据结构可以让我输入所有对象,然后它会根据出现的次数(例如按降序)返回对象。我能想到的就是使用哈希映射。哈希映射的键是对象,值是对象的出现。每次输入一个对象时,我都会增加相应键的值。但是这样的话,如果我想按照出现的降序输出对象,就需要遍历一次hash map。有没有更有效的方法在 Java 中实现这一点?

【问题讨论】:

标签: java data-structures


【解决方案1】:

SortedMap 可能是您最好的选择。您可以编写自己的比较器,使其按您喜欢的方式排序。

编辑:由于似乎存在混淆,这是一个按要求按降序排列的示例。

import java.util.*;
public class TestSortedMap {

    private static class CountComparator implements Comparator<String> {

        Map<String, Integer> map;
        public CountComparator(Map<String, Integer> map) {
            this.map = map;
        }

        public int compare(String a, String b) {
            if (map.get(a) < map.get(b)) return 1;
            else if (map.get(a) > map.get(b)) return -1;
            return 0;
        }
    }

    public static void main(String[] args) {

        Map<String, Integer> testInput = new HashMap<>();
        testInput.put("Hello", 10);
        testInput.put("World", 0);
        testInput.put("Let's", 40);
        testInput.put("Party", 30);
        System.out.println("Unordered:");
        for (String key: testInput.keySet()) {
            System.out.println("Key: " + key + " | Value: " + testInput.get(key));
        }

        CountComparator countComparator = new CountComparator(testInput);
        SortedMap<String, Integer> sortedMap = new TreeMap<>(countComparator);
        sortedMap.putAll(testInput);

        System.out.println("Ordered:");
        for (String key: sortedMap.keySet()) {
            System.out.println("Key: " + key + " | Value: " + sortedMap.get(key));
        }
    }
}

结果集:

Unordered:
Key: Party | Value: 30
Key: Hello | Value: 10
Key: Let's | Value: 40
Key: World | Value: 0
Ordered:
Key: Let's | Value: 40
Key: Party | Value: 30
Key: Hello | Value: 10
Key: World | Value: 0

【讨论】:

  • 不,我犯了同样的错误:SortedMap 和 TreeMap 是按键排序的,OP 正在寻找按值排序的数据结构
  • 来自文档:地图根据其键的自然顺序排序,或者由通常在排序地图创建时提供的比较器排序。
  • 确实,我就是这么写的……
  • 你能澄清一下吗?你一开始是对的,什么会阻止你编写一个按 SortedMap 或 TreeMap 的值排序的 Comparator?
  • 比较器将在键而不是值上激活。
猜你喜欢
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
相关资源
最近更新 更多