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.
  • These sort() methods uses compare method of 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.

Complete Code:



Output:

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

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: