Skip to content

Instantly share code, notes, and snippets.

@thmain
Created May 27, 2018 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/98a26f8ec8cd47ca2c65f3c523df51ca to your computer and use it in GitHub Desktop.
Save thmain/98a26f8ec8cd47ca2c65f3c523df51ca to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class SortUsingLastNames {
public void sortLast(ArrayList<String> al) {
Collections.sort(al, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String[] split1 = o1.split(" ");
String[] split2 = o2.split(" ");
String lastName1 = split1[1];
String lastName2 = split2[1];
if (lastName1.compareTo(lastName2) > 0) {
return 1;
} else {
return -1;
}
}
});
System.out.println(al);
}
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("Daenerys Targaryen");
al.add("Jon Show");
al.add("Tyrion Lannister");
al.add("Joffrey Baratheon");
SortUsingLastNames i = new SortUsingLastNames();
System.out.println("Sorted using Last Name");
i.sortLast(al);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment