可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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);
回答1:
Yes this is fairly trivial in Java 8:
Collections.sort(list, Comparator.comparing(s -> s.subString(4));
回答2:
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); } });
回答3:
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)));