Sorting arraylist in alphabetical order (case insensitive)

JavaSortingArraylist

Java Problem Overview


I have a string arraylist names which contains names of people. I want to sort the arraylist in alphabetical order.

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

Java Solutions


Solution 1 - Java

Custom Comparator should help

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:

list.sort(String::compareToIgnoreCase);

Solution 2 - Java

The simplest thing to do is:

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Solution 3 - Java

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
}

}

Solution 4 - Java

Based on the above mentioned answers, I managed to compare my custom Class Objects like this:

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

        });

Solution 5 - Java

Unfortunately, all answers so far do not take into account that "a" must not be considered equal to "A" when it comes to sorting.

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.

Approach 2 makes it worse, since CASE_INSENSITIVE_ORDER considers "a" and "A" equal (comparation result is 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.

Solution 6 - Java

You need to use custom comparator which will use compareToIgnoreCase, not compareTo.

Solution 7 - Java

Starting from Java 8 you can use 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). After that, the stream is converted to an array which is converted to an ArrayList.

If you print the result using:

System.out.println(sorted);

you get the following output:

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

Solution 8 - Java

KOTLIN DEVELOPERS

For Custome List, if you want to sort based on one String then you can use this:

phoneContactArrayList.sortWith(Comparator { item, t1 ->
        val s1: String = item.phoneContactUserName
        val s2: String = t1.phoneContactUserName
        s1.compareTo(s2, ignoreCase = true)
    })

Solution 9 - Java

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

Solution 10 - Java

Kotlin. Sorting objects by string fields, case insensitive.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionandro-girlView Question on Stackoverflow
Solution 1 - Javadenis.solonenkoView Answer on Stackoverflow
Solution 2 - JavadjunodView Answer on Stackoverflow
Solution 3 - JavahackerView Answer on Stackoverflow
Solution 4 - JavaUsmanView Answer on Stackoverflow
Solution 5 - JavaLars GendnerView Answer on Stackoverflow
Solution 6 - JavaVladimir IvanovView Answer on Stackoverflow
Solution 7 - JavaROMANIA_engineerView Answer on Stackoverflow
Solution 8 - JavaKishan SolankiView Answer on Stackoverflow
Solution 9 - JavaKidaneView Answer on Stackoverflow
Solution 10 - JavakulikovmanView Answer on Stackoverflow