4

Possible Duplicate:
Sorting arraylist in Android in alphabetical order (case insensitive)

Hi everybody I have a small problem in sorting.

I am taking one collection of type String. When I am sorting it is giving me the wrong result that I was expecting

Here is my code :

List <String> caps = new ArrayList<String>();  
caps.add("Alpha");  
caps.add("Beta");  
caps.add("alpha1");  
caps.add("Delta");  
caps.add("theta");  

Collections.sort(caps);

It is sorting like:

Alpha Beta Delta alpha1 theta.

Here it can take any type of string even uppercase / lowercase. But the lowercase words are coming later.

I want the out put like :

Alpha alpha1 Beta Delta theta

Is there an easy built-in method for this?

Community
  • 1
  • 1
Ethan Allen
  • 14,425
  • 24
  • 101
  • 194

2 Answers2

13

Collections.sort(); lets you pass a custom comparator for ordering. For case insensitive ordering String class provides a static final comparator called CASE_INSENSITIVE_ORDER.

So in your case all that's needed is:

Collections.sort(caps, String.CASE_INSENSITIVE_ORDER);

jlordo
  • 37,490
  • 6
  • 58
  • 83
1

Use a Comparator:

Collections.sort(caps, new Comparator<String>{
    public int compare(String s1, String s2){
        return s1.toLowerCase().compareTo(s2.toLowerCase());
    }
});
Mordechai
  • 15,437
  • 2
  • 41
  • 82
  • 1
    Use `compareToIgnoreCase` instead of this answer. – Christophe Roussy Nov 24 '14 at 13:42
  • @Mordechai's approach as well as `compareToIgnoreCase` are not correct, since both return `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:35