我必须计算单词的出现次数并按出现次数(按降序)显示它们。我可以数出单词数,但不知道如何继续。可能是我做事效率不高。如果可能,请提出解决方案。
import java.io.*;
import java.util.*;
public class MaxOccurence
{
public static void main(String[] args)
{
Map<String, Integer> map = new HashMap<>();
try
{
BufferedReader br = new BufferedReader(new FileReader(new File(
"F:/Demo/file_reading/bin/demo/hello.txt")));
String str;
while ((str = br.readLine()) != null)
{
Scanner sc = new Scanner(str);
while (sc.hasNext())
{
String word = sc.next();
if (map.containsKey(word))
map.put(word, map.get(word) + 1);
else
map.put(word, 1);
}
}
System.out.println("yes");
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println(map);
}
}
最佳答案
我认为您使用 HashMap
类和 map.containsKey
方法的方法对于您解决的字数统计是一种有效的方法,所以剩下的就是排序和打印 map 按降序排列,这里是一个关于如何实现此目的的干净而有效的示例:
map.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.forEachOrdered(System.out::println);
请注意,如果删除 Collection.reverseOrder
调用,则顺序将为升序。
将其添加到您的代码中将如下所示:
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class MaxOccurence {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
try {
BufferedReader br = new BufferedReader(new FileReader(new File(
"F:/Demo/file_reading/bin/demo/hello.txt")));
String str;
while ((str = br.readLine()) != null) {
Scanner sc = new Scanner(str);
while (sc.hasNext()) {
String word = sc.next();
if (map.containsKey(word))
map.put(word, map.get(word) + 1);
else
map.put(word, 1);
}
}
System.out.println("yes");
} catch (IOException e) {
e.printStackTrace();
}
map.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.forEachOrdered(System.out::println);
}
}
关于java - 按单词出现的降序显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29709986/