然后按字母顺序排列

然后按字母顺序排列

本文介绍了按值排序哈希表,然后按字母顺序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个可以很好地计算单词的单词频率程序。我正在使用散列图来存储单词频率。我用这个词作为关键词,并把这个词作为价值。但是,我想先按字频对hashMap进行排序,然后按字母顺序排序,如下所示:

  

您不能有一个排序的 HashMap :

您必须将其置于不同的结构中维持您想要订单的订单。



根据您提供的内容,您看起来似乎有一些订单标准:


$ $ b


  1. 按 Map.Entry 降序排列

  2. 按 Map.Entry 升序排列

您可以使用 Stream API以及有用的 Comparator s从 Map.Entry 。

  final HashMap< String,Integer> map = new HashMap<>(); 

map.put(it,2);
map.put(of,2);
map.put(the,2);
map.put(times,2);
map.put(was,2);
map.put(best,1);
map.put(worst,1);

System.out.println(无保证订单:);
map.entrySet()。stream()
.forEach(System.out :: println);


System.out.println();
System.out.println(With Ordering:);
map.entrySet()。stream()
.sorted(Map.Entry。< String,Integer> comparisonByValue()
.reversed()
.thenComparing(Map。 Entry.comparingByKey()))
.forEach(System.out :: println);

输出:

 无保证订单:
the = 2
times = 2
of = 2
was = 2
最好= 1
最差= 1
it = 2

订购时:
it = 2
of = 2
the = 2
次= 2
= 2
最好= 1
最差= 1


I am creating a word frequency program which works good with counting the words. I am using a hashmap to store the word frequencies. I use the word as the key and the count as the value. However, I want to sort the hashMap at the end first by the word frequency and then by key alphabetically like this:

it - 2
of - 2
the - 2
times- 2
was - 2
best- 1
worst - 1

I am guessing that I will need a custom Comparator, but I have no idea how to construct it. Please, any suggestions?

解决方案

You cannot have a sorted HashMap, as is stated in the Javadoc:

You will have to put it into a different structure that maintains the order you want it to.

Based on what you provided, it looks like you have a few criteria for your order:

  1. sorted by the Map.Entry value, in descending order
  2. sorted by the Map.Entry key, in ascending order

You can make use of the Stream API, along with the useful Comparators from Map.Entry.

final HashMap<String, Integer> map = new HashMap<>();

map.put("it", 2);
map.put("of", 2);
map.put("the", 2);
map.put("times", 2);
map.put("was", 2);
map.put("best", 1);
map.put("worst", 1);

System.out.println("No Guaranteed Order:");
map.entrySet().stream()
        .forEach(System.out::println);


System.out.println();
System.out.println("With Ordering:");
map.entrySet().stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue()
                        .reversed()
                .thenComparing(Map.Entry.comparingByKey()))
        .forEach(System.out::println);

And the output:

No Guaranteed Order:
the=2
times=2
of=2
was=2
best=1
worst=1
it=2

With Ordering:
it=2
of=2
the=2
times=2
was=2
best=1
worst=1

这篇关于按值排序哈希表,然后按字母顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:40