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.
You can provide a custom Comparator<String>
and call Collections.sort(List<T>, Comparator<T>)
, like
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
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.