[英]How to sort a Map by Value (ArrayList) size in Java?
我有以下地圖:
Map<String, List<String>> map = new HashMap<String, List<String>>();
其中填充有成對的鍵和值。
例如:鍵=學生姓名,值=家庭成員姓名。
我想按字符串列表的大小對地圖進行排序。 我曾嘗試用TreeMap實現Comparator,但遇到錯誤,所以我切換回HashMap。 有任何想法嗎?
您應該無序使用HashMap,然后每次要進行排序時,都要使用HashMap作為變量的Comparator將HashMap的所有值放入TreeMap中。
然后,對於您比較的每個鍵,您將獲得HashMap的值(列表)並檢查列表大小。 因此,您可以根據列表大小進行比較,並根據情況返回-1、0或1。
完成所需的操作后,將丟棄該TreeMap。
如果您嘗試僅使用TreeMap,則會看到您正在根據不是該鍵屬性的值對鍵進行排序。 在這種情況下,值的長度(列表)。 因此,可能存在增加列表長度的功能,並且TreeMap甚至不會注意到。
一些代碼:
public class ListSizeComparator implements Comparator<String> {
private final Map<String, List<String>> map;
public ListSizeComparator(final Map<String, List<String>> map) {
this.map = map;
}
@Override
public int compare(String s1, String s2) {
//Here I assume both keys exist in the map.
List<String> list1 = this.map.get(s1);
List<String> list2 = this.map.get(s2);
Integer length1 = list1.size();
Integer length2 = list2.size();
return length1.compareTo(length2);
}
}
該解決方案與https://stackoverflow.com/a/8897384/869736大致相同,但是您所需要做的就是編寫一個Comparator
,該Comparator
根據列表的長度比較列表。
Comparator<List<String>> lengthComparator = new Comparator<List<String>>() {
public int compare(List<String> a, List<String> b) {
return a.size() - b.size();
// size() is always nonnegative, so this won't have crazy overflow bugs
}
};
然后僅使用此處概述的解決方案。
我在這里看到三個選擇:
TreeMap<Integer, List<String>>
(鍵-家庭成員數量,值-學生列表)。 TreeMap<Integer, Map<String, List<String>>>
(鍵-家庭成員數量,值-您原始地圖的一部分包含家庭成員人數等於$ key的學生的地圖)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.