[英]Converting HashMap to Sorted ArrayList
我有一個HashMap<String, Integer>
包含單詞及其頻率。 我現在需要將此HashMap
轉換為僅包含單詞的ArrayList
,丟棄頻率,但我還希望ArrayList
以單詞的降序按頻率排序 。
有人知道這樣做的有效方法嗎?
HashMap
有一個方便的方法,稱為entrySet()
,使您可以訪問鍵-值對的集合。 您可以使用它來構造List<Map.Entry<String,Integer>>
。
現在,您可以進行排序了。 使用帶有自定義比較器的排序方法,該比較器將頻率較高的條目排序到列表的開頭。
手頭有一個已排序的列表,您所要做的就是走動它,然后按正確的順序收獲單詞。
List<Map.Entry<String,Integer>> entries = new ArrayList<Map.Entry<String,Integer>>(
freqMap.entrySet()
);
Collections.sort(
entries
, new Comparator<Map.Entry<String,Integer>>() {
public int compare(Map.Entry<String,Integer> a, Map.Entry<String,Integer> b) {
return Integer.compare(b.getValue(), a.getValue());
}
}
);
for (Map.Entry<String,Integer> e : entries) {
// This loop prints entries. You can use the same loop
// to get the keys from entries, and add it to your target list.
System.out.println(e.getKey()+":"+e.getValue());
}
使用Java 8時,您可以使用Stream API ,如下所示:
final Map<String, Integer> wordStats = new HashMap<>();
// some dummy data:
wordStats.put("twice", 2);
wordStats.put("thrice", 3);
wordStats.put("once", 1);
final List<String> sortedStats = wordStats.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue, Comparator.reverseOrder()))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
// or to specify the list implementation:
//.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
// Output
sortedStats.forEach(System.out::println);
輸出:
thrice
twice
once
在Java 8中,您還可以對已回答的內容進行這種簡短的修改
升序
ArrayList<Map.Entry<String, Integer>> sorted = newArrayList<>(frequencies.entrySet());
sorted.sort(Comparator.comparingInt(Map.Entry::getValue));
降序排列
ArrayList<Map.Entry<String, Integer>> sorted = new ArrayList<>(frequencies.entrySet());
sorted.sort(Collections.reverseOrder(Comparator.comparingInt(Map.Entry::getValue)));
您可以:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.