2016-09-20 67 views
0

我已经尝试了很多解决方案,我真的在这里苦苦挣扎。通过在每个字符串中的最后一个字的字符串迭代和Alphabetize ArrayList

我有一个长度不等的字符串列表。

我需要按字母顺序排序每个字符串中的最后一个字。

某些字符串被输入为“未知”,而其他字符串是多个单词。

例子:

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  

我如何可以遍历这个列表中每个字符串姓氏/字排序?

非常感谢您的任何建议。在此期间,我会继续使用谷歌。

回答

1

您可以提供自定义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] 
+0

无瑕。谢谢你的时间! – user1028872

1

在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); 
} 
相关问题