Android ignore case when sorting list

杀马特。学长 韩版系。学妹 提交于 2020-01-13 19:14:08

问题


I have a List named path I'm currently sorting my strings with the following code

  java.util.Collections.sort(path);

That is working fine it sorts my list however it treats the cases of the first letter differently that is it sorts the list with upper-case letters and then sorts the list with lower-case letters after so if I had the following cat dog Bird Zebra it would sort it like

Bird
Zebra
dog
cat

so how do I ignore case so that dog and cat would come before Zebra but after Bird? Thank you for any help


回答1:


Create a custom comparator class:

import java.util.Comparator;

class IgnoreCaseComparator implements Comparator<String> {
  public int compare(String strA, String strB) {
    return strA.compareToIgnoreCase(strB);
  }
}

Then on your sort:

IgnoreCaseComparator icc = new IgnoreCaseComparator();

java.util.Collections.sort(path,icc);



回答2:


Use the built-in String comparator String.CASE_INSENSITIVE_ORDER

java.util.Collections.sort(path, String.CASE_INSENSITIVE_ORDER);



回答3:


Collections.sort(path,new Comparator<String>(){
   public int compare(String strA, String strB) {
    return strA.compareToIgnoreCase(strB);
  }
});


来源:https://stackoverflow.com/questions/5454721/android-ignore-case-when-sorting-list

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