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 Comment

  1. hermes outlet October 18, 2013 at 4:41 am

    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

     

Leave a Reply

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

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.