[英]Array List of String Sorting Method
i have an Array List with Following values 我有一个具有以下值的数组列表
ArrayList [Admin,Readonly,CSR,adminuser,user,customer]
when i used 当我用的时候
Collections.sort(ArrayList)
i'm getting the Following Result 我得到了以下结果
[Admin,CSR,Readonly,adminuser,customer,user]
as per the Java doc the above results are correct, but my Expectation is (sorting irrespective of case (upper / lower case) 根据Java文档,上面的结果是正确的,但我的期望是(排序与案例无关(大/小写)
[Admin,adminuser,CSR,customer,Readonly,user]
provide an help how will do the sorting irrespective of case in java, is there any other method available 提供帮助如何进行排序,无论java中的情况如何,是否有任何其他方法可用
Note: i will do an Automate test for checking the sorting order in the Web table 注意:我将进行自动测试以检查Web表中的排序顺序
regards 问候
prabu prabu
This'll do, 这样做,
Collections.sort(yourList, String.CASE_INSENSITIVE_ORDER);
this is i have tried, 这是我试过的,
ArrayList<String> myList=new ArrayList<String>();
Collections.addAll(myList,"Admin","Readonly","CSR","adminuser","user","customer");
System.out.println(myList);
Collections.sort(myList, String.CASE_INSENSITIVE_ORDER);
System.out.println(myList);
the following output i got, 我得到以下输出,
[Admin, Readonly, CSR, adminuser, user, customer]
[Admin, adminuser, CSR, customer, Readonly, user]
You can use your own comparator like this to sort irrespective of case (upper / lower case) 您可以像这样使用自己的比较器进行排序,无论大小写(大小写)
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String s1, String s2)
{
return s1.compareToIgnoreCase(s2);
}
});
You can do with custom Comparator. 您可以使用自定义Comparator。
Try this: 尝试这个:
// list containing String objects
List<String> list = new ArrayList<>();
// call sort() with list and Comparator which
// compares String objects ignoring case
Collections.sort(list, new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
You will need to pass Comparator
instance in Collections.sort()
method which compares String
objects ignoring case. 您需要在
Collections.sort()
方法中传递Comparator
实例,该方法比较忽略大小写的String
对象。
public class SortIgnoreCase implements Comparator<Object> {
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
return s1.toLowerCase().compareTo(s2.toLowerCase());
}
}
then 然后
Collections.sort(ArrayList, new SortIgnoreCase());
Collections.sort(ArrayList, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.toLowerCase().compareTo(s2.toLowerCase());
}
});
Answer is simple - big letters have lower number in ASCII
. 答案很简单 - 大字母的
ASCII
数字较低。 So default comparing works fine. 所以默认比较工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.