I am trying to figure out how to sort my list alphabetically, normally this would be really easy, but I need to ignore the first 5 characters of each string in my list. (they are numerical IDS)
ArrayList<String> tempList = new ArrayList<String>();
for(String s : AddressBook){
tempList.add(s);
Collections.sort(tempList );
}
System.out.println(tempList);
You can do it by supplying your own Comparator implementation.
Collections.sort (tempList, new Comparator<String>() {
public int compare(String o1, String o2)
{
String sub1 = o1.substring (3);
String sub2 = o2.substring (3);
return sub1.compareTo (sub2);
}
});
Yes this is fairly trivial in Java 8:
Collections.sort(list, Comparator.comparing(s -> s.subString(4));
This answer applies for Java 8, improving performance and readability by using lambda expressions.
You might need to apply special string length checks (if your implementation provides Strings shorter than 6 characters).
Collections.sort (tempList, (o1, o2) -> o1.substring(5).compareTo(o2.substring(5)));
来源:https://stackoverflow.com/questions/33063218/is-it-possible-to-sort-a-an-array-list-while-ignoring-the-first-3-characters-in