Is it possible to sort a an array list while ignoring the first 3 characters in each string?

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

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))); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!