How to Sort a String array in Android.

By | June 15, 2012

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

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.

One thought on “How to Sort a String array in Android.

  1. hermes outlet

    menti one d gilner

    By the burlingtonhoteldeals.com/sitemap.html poin prada bags t humans get therefore to their hermes belt 50s, employed set forth far more tailored planning retirement life as well as get their selves a few questions. How much more long time do they might work? do they really conside prada bags r a lifestyle in re

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *