# 如何查找数组列表中出现频率最高的 20 个单词

2023-08-23 15:01:25

## 5 回答

TA贡献1839条经验 获得超15个赞

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个赞

class TextCounter{

String text;

int count;

}

TA贡献1813条经验 获得超2个赞

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个赞

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个赞

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> al = new ArrayList<>();

Item item = new Item(word, count);

Collections.sort(al);

• 5 回答
• 0 关注
• 145 浏览

0/150