简体   繁体   English

按字母顺序对 arraylist 进行排序(不区分大小写)

[英]Sorting arraylist in alphabetical order (case insensitive)

I have a string arraylist names which contains names of people.我有一个字符串 arraylist names ,其中包含人名。 I want to sort the arraylist in alphabetical order.我想按字母顺序对 arraylist 进行排序。

ArrayList<String> names = new ArrayList<String>();
names.add("seetha");
names.add("sudhin");
names.add("Swetha");
names.add("Neethu");
names.add("ananya");
names.add("Athira");
names.add("bala");
names.add("Tony");
names.add("Karthika");
names.add("Nithin");
names.add("Vinod");
names.add("jeena");
Collections.sort(names);
for(int i=0; i<names.size(); i++)
    System.out.println(names.get(i));

I tried to sort the list in above way.我试图以上述方式对列表进行排序。 But it is displaying the sorted array as:但它将排序数组显示为:

Athira
Karthika
..
..
ananya
bala
...

but I don't want to make it case sensitive.但我不想让它区分大小写。 I want the result as:我希望结果为:

ananya
Athira
bala

Custom Comparator should help自定义Comparator应该有帮助

Collections.sort(list, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }
});

Or if you are using Java 8:或者,如果您使用的是 Java 8:

list.sort(String::compareToIgnoreCase);

The simplest thing to do is:最简单的做法是:

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

try this code试试这个代码

Collections.sort(yourarraylist, new SortBasedOnName());



import java.util.Comparator;
import com.RealHelp.objects.FBFriends_Obj;
import com.RealHelp.ui.importFBContacts;

public class SortBasedOnName implements Comparator
{
public int compare(Object o1, Object o2) 
{

    FBFriends_Obj dd1 = (FBFriends_Obj)o1;// where FBFriends_Obj is your object class
    FBFriends_Obj dd2 = (FBFriends_Obj)o2;
    return dd1.uname.compareToIgnoreCase(dd2.uname);//where uname is field name
}

}

Based on the above mentioned answers, I managed to compare my custom Class Objects like this:基于上述答案,我设法比较了我的自定义 Class 对象,如下所示:

ArrayList<Item> itemList = new ArrayList<>();
...
Collections.sort(itemList, new Comparator<Item>() {
            @Override
            public int compare(Item item, Item t1) {
                String s1 = item.getTitle();
                String s2 = t1.getTitle();
                return s1.compareToIgnoreCase(s2);
            }

        });

Unfortunately, all answers so far do not take into account that "a" must not be considered equal to "A" when it comes to sorting.不幸的是,到目前为止,所有答案都没有考虑到在排序时不能将"a"视为等于"A"

String[] array = {"b", "A", "C", "B", "a"};

// Approach 1
Arrays.sort(array);
// array is [A, B, C, a, b]

// Approach 2
Arrays.sort(array, String.CASE_INSENSITIVE_ORDER);
// array is [A, a, b, B, C]

// Approach 3
Arrays.sort(array, java.text.Collator.getInstance());
// array is [a, A, b, B, C]

In approach 1 any lower case letters are considered greater than any upper case letters.在方法 1 中,任何小写字母都被认为大于任何大写字母。

Approach 2 makes it worse, since CASE_INSENSITIVE_ORDER considers "a" and "A" equal (comparation result is 0 ).方法 2 使情况变得更糟,因为 CASE_INSENSITIVE_ORDER 认为"a""A"相等(比较结果为0 )。 This makes sorting non-deterministic.这使得排序变得不确定。

Approach 3 (using a java.text.Collator) is IMHO the only way of doing it correctly, since it considers "a" and "A" not equal, but puts them in the correct order according to the current (or any other desired) Locale.方法 3(使用 java.text.Collator)是恕我直言唯一正确的方法,因为它认为"a""A"不相等,但根据当前(或任何其他所需的) 语言环境。

You need to use custom comparator which will use compareToIgnoreCase , not compareTo.您需要使用将使用compareToIgnoreCase的自定义比较器,而不是 compareTo。

Starting from Java 8 you can use Stream :Java 8开始,您可以使用Stream

List<String> sorted = Arrays.asList(
                          names.stream().sorted(
                              (s1, s2) -> s1.compareToIgnoreCase(s2)
                          ).toArray(String[]::new)
                      );

It gets a stream from that ArrayList , then it sorts it (ignoring the case).它从 ArrayList 获得ArrayList ,然后对其进行排序(忽略大小写)。 After that, the stream is converted to an array which is converted to an ArrayList .之后, stream 被转换为一个数组,该数组被转换为一个ArrayList

If you print the result using:如果您使用以下方法打印结果:

System.out.println(sorted);

you get the following output:您会得到以下 output:

[ananya, Athira, bala, jeena, Karthika, Neethu, Nithin, seetha, sudhin, Swetha, Tony, Vinod]

KOTLIN DEVELOPERS KOTLIN 开发者

For Custome List , if you want to sort based on one String then you can use this:对于Custome List ,如果您想基于一个 String 进行排序,那么您可以使用:

phoneContactArrayList.sortWith(Comparator { item, t1 ->
        val s1: String = item.phoneContactUserName
        val s2: String = t1.phoneContactUserName
        s1.compareTo(s2, ignoreCase = true)
    })
def  lst = ["A2", "A1", "k22", "A6", "a3", "a5", "A4", "A7"]; 

println lst.sort { a, b -> a.compareToIgnoreCase b }

This should be able to sort with case insensitive but I am not sure how to tackle the alphanumeric strings lists这应该能够以不区分大小写的方式进行排序,但我不确定如何处理字母数字字符串列表

Kotlin. Kotlin。 Sorting objects by string fields, case insensitive.按字符串字段排序对象,不区分大小写。

items?.sortedWith { o1, o2 ->
            o1.name.compareTo(o2.name, true)
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM