130

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
k3b
  • 14,517
  • 7
  • 53
  • 85
andro-girl
  • 7,989
  • 22
  • 71
  • 94

10 Answers10

352

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);
grg
  • 5,023
  • 3
  • 34
  • 50
denis.solonenko
  • 11,645
  • 2
  • 28
  • 23
  • 1
    can u tell me what is string s1 and s2?and how can see the result if the compare function returning integer value. – andro-girl Apr 28 '11 at 08:01
  • @seethalakshmi that's the strings from your list. Please take a look at the sources of Collections.sort method if you want to get more details on that – denis.solonenko Apr 28 '11 at 08:02
  • i want to display the sorted list in logcat.how can i do that? – andro-girl Apr 28 '11 at 08:11
  • It will appear as an Object, unless you break down the list with a loop after sorting. `for (TYPE newvariable : ARRAYTYPE arrayname) { Log.i("YOURAPPTAG", newvariable); }` – Abandoned Cart May 22 '13 at 20:13
  • @denis.solonenko, thanks for the answer. I've tried your solution for the ArrayList from A1 thru A10, but the A10 didn't sort correctly. Somehow, the A10 goes after A1. Basically, it sorted like A1, A10, A2, A3, etc. Why did it happen and how can I sort list correctly? – Dante Oct 05 '14 at 16:38
  • 2
    @Dante if you take a look at hthe implementation of `String.CASE_INSENSITIVE_ORDER`, then you'll see that A1 is condired `less` than A10 just because the lenght is smaller. There is no "natural sort" support out of the box, you might want to take a look at http://stackoverflow.com/questions/1262239/natural-sort-order-string-comparison-in-java-is-one-built-in – denis.solonenko Oct 07 '14 at 08:22
  • am using this code working fine. i need get data between two dates(start,end) from arraylist..how can i change that code? – sasikumar Sep 28 '15 at 14:19
  • @Dante Maybe I am to late to explain this but other can see and understand this. The problem is why A10 is between A1 and A2. Because when shorting using string is looking word one by one like AA, AB, BA, BB. So it will sort the first word and then the second word. So A10 and A2 will short A first and sort 1 with 2. Length not affected by this. So to make it sort just add 0 before 2 like A01, A02, ...., A10. – Akirayjin Aug 03 '16 at 07:43
  • `compareToIgnoreCase` is not correct, since it returns `0` when comparing `"a"` and `"A"`. In a sorting context, this is not correct. Upper- and lower case versions of a character should be put in a well-defined order. – Lars Gendner Aug 20 '19 at 08:38
206

The simplest thing to do is:

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
djunod
  • 4,876
  • 2
  • 34
  • 28
  • @djunod, thanks for the answer. I've tried also your solution for the ArrayList from A1 thru A10, but the A10 didn't sort correctly just like denis.solenenko's solution. Somehow, the A10 goes after A1. Basically, it sorted like A1, A10, A2, A3, etc. Why did it happen and how can I sort list correctly? – Dante Oct 05 '14 at 16:39
  • 2
    @dante, that is normal string sorting. If you want A2 to come before A10, you will have to change it to A02, etc. – djunod Oct 07 '14 at 22:47
  • 1
    Plus 1. Worked in Android too. Thanks and congrats. – statosdotcom May 16 '17 at 16:14
  • @djunod Thank U very much :) – Kumar Jan 10 '18 at 11:50
  • 2
    stackoverflow should provide me an option to save answers/snippets like this.. – HB. Oct 28 '19 at 18:20
30

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
}

}
hacker
  • 8,919
  • 12
  • 62
  • 108
  • 3
    Great answer! I think if you change 'implements Comparator' to 'implements Comparator and you change the Object types in the compare to FBFriends_Obj then you don't need dd1 and dd2 you can use o1 and o2 directly in the return statement – FrinkTheBrave Jul 19 '12 at 23:28
15

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

        });
Usman
  • 2,331
  • 2
  • 21
  • 29
6

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.

Lars Gendner
  • 1,816
  • 2
  • 14
  • 24
4

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]
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
4

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

Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
0
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

Kidane
  • 127
  • 1
  • 4
0

Kotlin. Sorting objects by string fields, case insensitive.

items?.sortedWith { o1, o2 ->
            o1.name.compareTo(o2.name, true)
        }
kulikovman
  • 333
  • 4
  • 8
-1

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)
    })
Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82