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?

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

You can do this with arrays as well......Arrays.sort(files, String.CASE_INSENSITIVE_ORDER);
1

Use a Comparator:

Collections.sort(caps, new Comparator<String>{
    public int compare(String s1, String s2){
        return s1.toLowerCase().compareTo(s2.toLowerCase());
    }
});

2 Comments

Use compareToIgnoreCase instead of this answer.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.