将HashMap转换为Sorted ArrayList

Dom*_*azi 1 java collections arraylist hashmap

我有一个HashMap<String, Integer>包含单词及其频率.我现在需要这种转换HashMapArrayList刚的话,频率丢弃,但我也想ArrayList按降序排列的频率词.

有谁知道这样做的有效方法?

ifl*_*oop 8

使用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);
Run Code Online (Sandbox Code Playgroud)

输出:

thrice
twice
once
Run Code Online (Sandbox Code Playgroud)


das*_*ght 7

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());
}
Run Code Online (Sandbox Code Playgroud)

演示.