Monday, April 30, 2012

How to Sort a String array in Android.


How to Sort a String array in Android.



Hello all….
This is a simple example showing how to sort a string array which is a arraylist in android.
we sort the array using the “Collections” class in android.
Here is a simple example
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.coderzheaven.pack;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import android.app.Activity;
import android.os.Bundle;
 
public class SortingStringsDemo extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        ArrayList<String> my_array = new ArrayList<String>();
 
          //Add elements to Arraylist
          my_array.add("CoderzHeaven");
          my_array.add("Google");
          my_array.add("Android");
          my_array.add("apple");
          my_array.add("android");
          my_array.add("Microsoft");
          my_array.add("Samsung");
 
          //sorting function
          Collections.sort(my_array);
 
          //display elements of ArrayList
          System.out.println("ArrayList elements after sorting in ascending order : ");
          System.out.println(Arrays.toString(my_array.toArray()));
 
          System.out.println("ArrayList elements Comparing - ignorecase");
          IgnoreCaseComparator icc = new IgnoreCaseComparator();
          java.util.Collections.sort(my_array,icc);
          Collections.sort(my_array);
          System.out.println(Arrays.toString(my_array.toArray()));
 
          System.out.println("Reversing the ArrayList");
          Collections.sort(my_array, Collections.reverseOrder());
          System.out.println(Arrays.toString(my_array.toArray()));
    }
 
    class IgnoreCaseComparator implements Comparator<String> {
      public int compare(String strA, String strB) {
        return strA.compareToIgnoreCase(strB);
      }
    }
}
Take a look at the LogCat for the output.

No comments: