嘿,我需要计算单词的频率并返回一个列出它们的字符串.我必须省略少于4个字符的单词和计数小于10的单词.我必须把它们从最高点到最低点排序,如果数量相同,还要按字母顺序排序.
import java.util.*;
import java.util.stream.*;
public class Words {
public String countWords(List<String> lines) {
String text = lines.toString();
String[] words = text.split("(?U)\\W+");
Map<String, Long> freq = Arrays.stream(words).sorted()
.collect(Collectors.groupingBy(String::toLowerCase,
Collectors.counting()));
LinkedHashMap<String, Long> freqSorted = freq.entrySet().stream()
.filter(x -> x.getKey().length() > 3)
.filter(y -> y.getValue() > 9)
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue, (oldValue, newValue) -> oldValue,
LinkedHashMap::new));
return freqSorted.keySet().stream()
.map(key -> key + " - " + freqSorted.get(key))
.collect(Collectors.joining("\n", "", ""));
}
}
我不能改变这个方法的论点.在按值排序后,我很难按字母顺序排序.try 使用thenCompare,但无法使其工作.除此之外,我非常感谢任何关于如何减少行数的反馈,这样我就不必流3次.