Be the first user to complete this post

  • 0
Add to List
Beginner

150. Sort Names by their Last Names.

Objective: Given a list of names ( first name and last name), sort the list by their last names.

Example:

List [] = {"Daenerys Targaryen", "Jon Snow", " Tyrion Lannister", " Joffrey Baratheon"}

Output: [Joffrey Baratheon, Tyrion Lannister, Jon Show, Daenerys Targaryen]

Approach:

  • We have sort() and Collections.sort() but we cannot do the normal sorting because we need to sort it using the Last Names.
  • This sort () method uses compare method of the Comparator class to sort the data so we need to override the compare().

Inside the compare(), we need to split the name (First Name and Last Name) and compare the last names.

Code:


Output:

Sorted using Last Name
[Joffrey Baratheon, Tyrion Lannister, Jon Show, Daenerys Targaryen]