2014-11-03 65 views
-2

我有一個HashMap<String, Integer>包含單詞及其頻率。我現在需要現在把這個HashMap轉換成只是字的ArrayList,丟棄的頻率,但我也希望ArrayList按降序排序按字頻。將HashMap轉換爲排序ArrayList

有沒有人知道一個有效的方法來做到這一點?

+4

這是一個非常標準的要求,你應該很容易能夠在互聯網上找到東西。你有沒有嘗試過嗎? – Michael 2014-11-03 15:32:43

+0

例如,您可以創建一個'Word'類來保存'String'和頻率,並實現'Comparable'接口比較'Word'對象的頻率。然後從'HashMap'填充一個'ArrayList ',然後調用'Collections.sort(yourArrayList)' – nem035 2014-11-03 15:35:48

+0

我最近準備了一些工作。我不知道這是否是最好的解決方案,而是使用'ArrayList ',而不是'Map ',其中MyClass包含字符串字和int/。你可以使用'Collections.sort(yourList,new Comparator (){@Override public int compare(MyClass mc1,MyClass mc2){...}});'將其排序 – 2014-11-03 15:36:00

回答

3

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()); 
} 

Demo.

0

您可以:

  • 把你的地圖中定義自己的比較一個SortedMap。
  • 將排序映射的keySet轉換爲列表。
2

當使用的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((e1, e2) -> e2.getValue().compareTo(e1.getValue())) 
    .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 
0

在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)));