[英]Sorting maps without a comparator, an arraylist, or a treeset
存储网页上找到的单词并将其与出现次数进行映射后,您将如何按频率(从最高到最低)对它们进行排序?
我可以访问的唯一导入是Arrays,HashMap,HashSet,Map和Set。 我研究了如何做到这一点,但似乎大多数人建议使用比较器或迭代器,我不想实现。
地图设置如下:Map found = new HashMap <>();
这是我到目前为止所拥有的:
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import util.WebDoc;
public class Sorting{
public static void main(String[] args) throws IOException {
String url;
url = “INSERT URL HERE”;
final int numPairs = 30; // maximum number of pairs to print
// get body of the web document
String content = WebDoc.getBodyContent(url);
String word_pattern = "[A-Za-z]{5,}";
Map<String, Integer> found = new HashMap<>(); // (word,frequency)
Matcher match = Pattern.compile(word_pattern).matcher(content);
int unique = 0;
while (match.find()) {
String word = match.group().toLowerCase();
System.out.println(word);
if (found.containsKey(word)){
if (found.get(word)==1)
unique--;
found.put(word, found.get(word) +1);
}
else{
found.put(word, 1);
unique++;
}
}
}
如果您改变主意使用基本的JDK实用程序,这里有一种方法可以使用流:
List<String> sorted = found.entrySet()
.stream()
.sort(Comparator.comparing(Map.Entry::getValue).reversed())
.map(Map.Entry::getKey)
.collect(Collectors.toList());
你不能。 HashMaps未排序或排序,因为其元素的位置基于对象哈希。
在此任务中有一些很好的替代方法按值(Java)对Map <Key,Value>进行排序 。
请检查一下: 我应该使用什么Java Collection?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.