Created
May 27, 2018 06:47
-
-
Save thmain/98a26f8ec8cd47ca2c65f3c523df51ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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