简体   繁体   English

按每个字符串中的最后一个单词迭代并按字母顺序排列字符串的ArrayList

[英]Iterate and Alphabetize ArrayList of Strings by Last Word in Each String

I've tried numerous solutions and am really struggling here. 我尝试了许多解决方案,并且在这里确实很挣扎。

I have an arraylist full of strings ranging in length. 我有一个充满字符串的数组列表,长度不等。

I need to sort the strings alphabetically by the last word in each string. 我需要按每个字符串中的最后一个单词按字母顺序对字符串进行排序。

Some strings are entered as "Unknown" while others are multiple words. 有些字符串输入为“未知”,而另一些则是多个单词。

Example: 例:

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);

Should return: 应该返回:

Hodor
Sir Jamie Lannister
Jon Snow
Unknown    

How can i iterate this list sorting by the last name / word in each string? 如何按每个字符串中的姓氏/单词迭代此列表?

Thanks immensely for any suggestions. 非常感谢您的任何建议。 I Will continue to google in the meantime. 在此期间,我将继续使用Google。

You can provide a custom Comparator<String> and call Collections.sort(List<T>, Comparator<T>) , like 您可以提供一个自定义的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);

Which outputs (as requested) 哪些输出(根据要求)

[Hodor, Sir Jamie Lannister, Jon Snow, Unknown]

in Java 8, this might work 在Java 8中,这可能有效

public void sort(List<String> authors) {
    Collections.sort((l, r) -> lastWord(l).compareTo(lastWord(r); )
}

public String lastWord(String str) {
    return str.substring(str.lastIndexOf(' ') + 1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM