Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Sort Names by their Last Names.

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

Exam­ple:

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 can­not do the nor­mal sort­ing because we need to sort it using the Last Names.
  • These sort() meth­ods uses com­pare method of Com­para­tor class to sort the data so we need to over­ride the compare().

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

Com­plete Code:

Out­put:

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

You may also like...