我认为您可以将 lambda 传递给List.<b>sort</b>:
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
String sentence = "it was the best of times it was the worst of times";
List<String> wordsWithCounts = getWordsWithCountsFromSentence(sentence);
System.out.println("Before sorting on counts then alphabetically:");
System.out.println(wordsWithCounts);
wordsWithCounts.sort((s1, s2) -> {
String[] s1Split = s1.split(" ");
String[] s2Split = s2.split(" ");
String s1Count = s1Split.length != 0 ? s1Split[s1Split.length - 1] : "";
String s2Count = s2Split.length != 0 ? s2Split[s2Split.length - 1] : "";
if (!s1Count.equals(s2Count)) {
return s2Count.compareTo(s1Count); // decreasing order based on counts
}
return s1.compareTo(s2); // alphabetically otherwise if same counts
});
System.out.println("After sorting on counts then alphabetically:");
System.out.println(wordsWithCounts);
}
private static List<String> getWordsWithCountsFromSentence(String sentence) {
Map<String, Integer> wordCounts = new LinkedHashMap<>(); // To maintain insertion order for before output
for (String word : sentence.split(" ")) {
wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);
}
return wordCounts.entrySet()
.stream()
.map(entry -> String.join(" - ", entry.getKey(), String.valueOf(entry.getValue())))
.collect(Collectors.toList());
}
}
输出:
Before sorting on counts then alphabetically:
[it - 2, was - 2, the - 2, best - 1, of - 2, times - 2, worst - 1]
After sorting on counts then alphabetically:
[it - 2, of - 2, the - 2, times - 2, was - 2, best - 1, worst - 1]
注意上述输出与您的预期输出之间的差异是因为t<i><b>h</b></i>e 在字典上位于t<i><b>i</b></i>mes 之前,如果计数相同,则上述代码默认为。