5 回答
TA贡献1839条经验 获得超15个赞
将单词视为哈希图,其中单词为键,计数为值。
LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();
words.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));
List<String> finalList = reverseSortedMap.entrySet()
.stream()
.map(entry -> entry.getKey())
.limit(20)
.collect(Collectors.toList());
TA贡献1858条经验 获得超8个赞
您可以创建一个类 TextCounter 并将其添加到基于地图收集的数据的列表中
class TextCounter{
String text;
int count;
}
现在按他的计数值排序
TA贡献1813条经验 获得超2个赞
假设您想要列出前 20 个单词及其在地图中的频率,从文件中读取单词,java-8 解决方案将是
LinkedHashMap<String, Long> top20WordsByFrequency = null;
try {
// Convert a file into stream of lines
top20WordsByFrequency = Files.lines(Paths.get("src/Fajl/blab"))
// convert lines into words
.flatMap(line -> Arrays.stream(line.toLowerCase().split("([,.\\\\s]+)")))
// make a map by grouping by key as word and value as the count of the word
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream()
// sort the map based on values (frequency) in reverse order and limit the map
// to 20
.sorted(Entry.comparingByValue(Comparator.reverseOrder())).limit(20)
// after limiting sort based on keys in descending order
.sorted(Map.Entry.<String, Long>comparingByKey().reversed())
// preserve the order in a LinkedHashMap
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (u, v) -> u, LinkedHashMap::new));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(top20WordsByFrequency);
TA贡献1810条经验 获得超4个赞
使用流 API 怎么样:
String[] words = {"one", "two", "two", "three", "three", "three"};
Map<String, Long> result =
Arrays.stream(words)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
第二部分:
List<Long> collect = result.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.limit(20)
.map(Map.Entry::getValue)
.collect(Collectors.toList());
System.out.println(collect);
TA贡献1846条经验 获得超7个赞
假设您的 findWords() 函数工作正常,并且您拥有所有单词及其计数,您可以执行以下操作:
因为您必须打印特定单词的计数。因此,您可以首先定义一个具有属性内容和计数的 Word 类,并定义一个默认比较器。如下所示:
class Item implements Comparable<Item>{
String word;
int count;
public Item(String word, int count){
this.count = count;
this.word = word;
}
public int compareTo(Item word){
//sorting in descending order
return word.count - this.count;
}
public String toString(){
return "Word: " + word +"Count: " + count;
}}
定义一个项目 ArrayList 来保存 Item 对象:
ArrayList<Item> al = new ArrayList<>();
您可以迭代整个哈希图,然后将每对插入为:
Item item = new Item(word, count);
al.add(item);
最后,您可以对列表进行排序,然后选择前 20 个单词:
Collections.sort(al);
添加回答
举报