我有一個系統來檢查哈希表中的值排序,它用于獲取該哈希表中的頂部字串。我想在那個 Hashtable 中設定另一個值,所以我在里面使用了一個類,就像這樣:
Map<String, Values> hash = new Hashtable<String,Values>();
班上:
public class Values {
public Integer a;
public Integer b;
public Values(Integer a, Integer b) {
this.a = a;
this.b = b;
}
}
我的目標是對哈希表(整數 a 和 b)中的所有值進行排序并回傳哈希表字串,顯示誰具有最高值,(如資料庫系統)是否可以這樣做?我想這樣做的原因是為了在游戲中按整數 a 排序獲得最好的殺手,并在整數 b 中設定最后一次擊殺的時間,所以如果玩家在另一個之前擊殺并且擁有相同數量的擊殺它首先顯示具有最高整數 b 的那個,這將是變數 b 中具有最高時間(毫秒)的那個。
做這樣的事情的最佳方法是什么?
uj5u.com熱心網友回復:
編輯:編輯帖子以對整體進行排序entrySet()。
要獲得自定義排序順序,您將定義一個 Comparator<Map.Entry<String, Values>>,指定您想要比較地圖條目的順序,以及是否應該反向完成排序的任何部分(下降)。
根據您的描述,我認為您想a成為第一個降序排序的人,然后b也成為降序排序的人。
Comparator<Map.Entry<String, Values>> myValuesComparator = Comparator
.comparingInt((Map.Entry<String, Values> entry) -> entry.getValue().a)
.thenComparingInt(entry -> entry.getValue().b)
.reversed();
然后你hash.entrySet()通過呼叫將你變成一個流.stream(),然后你用你的比較器通過呼叫對條目流進行排序.sorted(myValuesComparator)。最后您將排序的條目收集到一個新的集合中,我們將它們收集到一個List<Map.Entry<String, Values>>這里。
List<Map.Entry<String, Values>> list = hash.entrySet()
.stream()
.sorted(myValuesComparator)
.collect(Collectors.toList());
如果要檢查結果,可以放置斷點并檢查串列中的元素,或者只列印整個串列
for (Map.Entry<String, Values> entry : list) {
System.out.printf("Key: %s, score: %d, time of last update: %d%n", entry.getKey(), entry.getValue().a, entry.getValue().b);
}
正如 Mark Rotteveel 在評論中所建議的那樣,如果您將您的代碼更改Hashtable為 a HashMap,同樣的代碼也可以作業,因為它Hashtable被認為是一個過時的類。
這是我的示例輸出
Key: Test9, score: 11, time of last update: 3
Key: Test8, score: 11, time of last update: 2
Key: Test7, score: 11, time of last update: 1
Key: Test6, score: 10, time of last update: 3
Key: Test5, score: 10, time of last update: 2
Key: Test4, score: 10, time of last update: 1
Key: Test3, score: 1, time of last update: 3
Key: Test2, score: 1, time of last update: 2
Key: Test1, score: 1, time of last update: 1
用于輸入
hash.put("Test1", new Values( 1, 1));
hash.put("Test2", new Values( 1, 2));
hash.put("Test3", new Values( 1, 3));
hash.put("Test4", new Values(10, 1));
hash.put("Test5", new Values(10, 2));
hash.put("Test6", new Values(10, 3));
hash.put("Test7", new Values(11, 1));
hash.put("Test8", new Values(11, 2));
hash.put("Test9", new Values(11, 3));
uj5u.com熱心網友回復:
設定鍵 = hash.keySet();
keys.stream().forEach(System.out::println);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/405604.html
標籤:
