問題描述
這是我第一次在 Java 中訂購 HashMap
.我需要按鍵來做到這一點(diǎn),但在我的情況下,按鍵是一個(gè)對象,所以我需要按特定字段排序.試圖自己弄清楚,我考慮過繼續(xù)這個(gè)簡單的代碼:
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;
}
假設(shè)它可以工作并且我不關(guān)心性能,在真正使用它之前,我想知道下一段代碼是否會(huì)更好,最重要的是:為什么?
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 進(jìn)行排序
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;
}
如果兩者都錯(cuò)了,我該怎么做?
If both are wrong, how should I do that?
推薦答案
您無法控制 HashMap
的排序.一個(gè) LinkedHashMap
只是一個(gè)具有可預(yù)測迭代順序的 HashMap
- 這是朝著正確方向邁出的一步,但它仍然使事情過于復(fù)雜.Java 有一個(gè)用于排序地圖的內(nèi)置接口(其名稱并不奇怪 SortedMap
),以及幾個(gè)實(shí)現(xiàn),最流行的是 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);
}
這篇關(guān)于在 Java 中按鍵排序 HashMap 的最佳方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!