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);
添加回答
舉報