我尝试了多种解决方案,但在这里真的很挣扎。
我有一个数组列表,其中充满了长度不等的字符串。
我需要按每个字符串中最后一个单词的字母顺序对字符串进行排序。
某些字符串输入为“未知”,而其他字符串则为多个单词。
示例:
static List<String> authors = new ArrayList<>();
authors.add("Unknown");
authors.add("Hodor");
authors.add("Jon Snow");
authors.add("Sir Jamie Lannister");
sort(authors);
System.out.println(authors);
应该返回:
Hodor
Sir Jamie Lannister
Jon Snow
Unknown
如何迭代此列表并按每个字符串中的姓氏/单词排序?
非常感谢您的任何建议。在此期间我将继续谷歌。
最佳答案
您可以提供自定义Comparator<String>
并调用 Collections.sort(List<T>, Comparator<T>)
,比如
List<String> authors = new ArrayList<>(Arrays.asList("Unknown", "Hodor", "Jon Snow",
"Sir Jamie Lannister"));
Collections.sort(authors, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String[] left = o1.split("\\s+");
String[] right = o2.split("\\s+");
return left[left.length - 1].compareTo(right[right.length - 1]);
}
});
System.out.println(authors);
哪个输出(根据要求)
[Hodor, Sir Jamie Lannister, Jon Snow, Unknown]
关于java - 按每个字符串中的最后一个单词迭代字符串的 ArrayList 并按字母顺序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39584126/