0

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.

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Flawless. Thanks for your time!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.