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

China☆狼群 提交于 2019-12-04 12:52:29

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