在 Java 中按键排序 HashMap 的最佳方法?

这是我第一次在 Java 中订购 HashMap.我需要按键来做到这一点,但在我的情况下,按键是一个对象,所以我需要按特定字段排序.试图自己弄清楚,我考虑过继续这个简单的代码:

This is the first time that I have to order an HashMap in Java. I need to do that by key but in my case the key is an object so I need to order by a specific field. Trying to figure it by my own I've considered to proceed with this simple scratch of code:

private HashMap<SimpleDBField, String> sortTable(HashMap<SimpleDBField, String> row){

    LinkedHashMap<SimpleDBField, String> orderedRow = new LinkedHashMap<SimpleDBField, String>();

    for(int i = 1; i <= row.size(); i ++){
        Iterator iterator = row.entrySet().iterator();

        while(iterator.hasNext()){
            Map.Entry<SimpleDBField, String> entry = (Map.Entry<SimpleDBField, String>) iterator.next();

            if(entry.getKey().getListPosition()==i){
                orderedRow.put(entry.getKey(), entry.getValue());
                break;
            }
        }
    }

    return orderedRow;
}

假设它可以工作并且我不关心性能,在真正使用它之前,我想知道下一段代码是否会更好,最重要的是:为什么?

Assuming that it works and I don't care about performance, before really use it, I wish to know if the next scratch of code could be better and most important: Why?

以下来源示例:如何在 Java 中按键和值对 HashMap 进行排序

public static <K extends Comparable,V extends Comparable> Map<K,V> sortByKeys(Map<K,V> map){

    List<K> keys = new LinkedList<K>(map.keySet());

    Collections.sort(keys);

    Map<K,V> sortedMap = new LinkedHashMap<K,V>();

    for(K key: keys){
        sortedMap.put(key, map.get(key));

    }

    return sortedMap;
}

如果两者都错了,我该怎么做?

If both are wrong, how should I do that?

推荐答案

您无法控制 HashMap 的排序.一个 LinkedHashMap只是一个具有可预测迭代顺序的 HashMap - 这是朝着正确方向迈出的一步,但它仍然使事情过于复杂.Java 有一个用于排序地图的内置接口(其名称并不奇怪 SortedMap),以及几个实现,最流行的是 TreeMap.只需使用它,让 Java 完成所有繁重的工作:

You cannot control a HashMap's ordering, as you've seen. A LinkedHashMap is just a HashMap with a predictable iteration order - it's a step in the right direction, but it's still over-complicating things. Java has a built-in interface for sorted maps (with the unsurprising name SortedMap), and a couple of implementation, the most popular one being a TreeMap. Just use it and let Java do all the heavy lifting:

public static <K extends Comparable, V> Map<K,V> sortByKeys(Map<K,V> map) {
    return new TreeMap<>(map);
}

相关文章