【发布时间】:2016-04-27 02:38:17
【问题描述】:
存储在网页上找到的单词并将它们与其出现次数进行映射后,您将如何按频率(从高到低)对它们进行排序?
我可以访问的唯一导入是 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++;
}
}
}
【问题讨论】:
-
你确定你不是Paul?
-
"...大多数人建议使用比较器或迭代器..." -- 这是有原因的 -- "...我不这样做不想实施。” -- 为什么不呢?
-
如果有人想让你在没有迭代器的情况下编写代码,那么他们要么是巨魔,要么不知道迭代器是什么。