java - 如何根据Java中的最后一个字符对数组列表进行排序?
问题描述
我有一个数组列表,它显示字符串的每个唯一单词以及它们出现的次数(每个元素都是一个字符串)
但是我想根据最后一个字符(即计数)对数组列表进行排序,有没有方法去做这个?
示例:
"it was the best of times it was the worst of times"
was - 2
best - 1
it - 2
the - 2
times - 2
of - 2
worst - 1
预期输出:
it - 2
of - 2
times - 2
the - 2
was - 2
best - 1
worst - 1
解决方案
我认为您可以将 lambda 传递给:List.sort
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]
注意上述输出与您的预期输出之间的差异是因为在字典顺序之前出现,如果计数相同,上述代码默认为。the
times
推荐阅读
- python - 非负整数组成的高效枚举
- typescript - 当 TypeScript 存在额外属性时创建类型错误
- javascript - 将关联续集到同一张表
- python - 快速迭代大型数据帧中的行以确定列的内容
- emacs - 如何从组织模式表生成源代码?
- angular - @connection 上的 AWS Amplify Graphql 查询
- reactjs - 如何从 React UL/LI 中删除 HTML
- node.js - 将数据添加到 cart.json 文件(异步调用)
- flex-lexer - 如何区分 Lex 中的加号运算符和正号?
- c++ - 有没有办法定义相同类型的可变数量的参数?