Monday, 29 April 2013

ArrayList Sorting in android


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 TestActivity extends Activity {
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            ArrayList<String> ar_hb = new ArrayList<String>();

            //Add elements to Arraylist
            ar_hb.add("Mayank");
            ar_hb.add("Maku");
            ar_hb.add("Mukesh");
            ar_hb.add("Igroup");

            //sorting function
            Collections.sort(ar_hb);

            //display elements of ArrayList
            System.out.println("ArrayList elements after sorting in ascending order : ");
            System.out.println(Arrays.toString(ar_hb.toArray()));

            System.out.println("ArrayList elements Comparing - ignorecase");
            IgnoreCaseComparator icc = new IgnoreCaseComparator();
            java.util.Collections.sort(ar_hb,icc);
            Collections.sort(ar_hb);
            System.out.println(Arrays.toString(ar_hb.toArray()));

            System.out.println("Reversing the ArrayList");
            Collections.sort(ar_hb, Collections.reverseOrder());
            System.out.println(Arrays.toString(ar_hb.toArray()));
      }

      class IgnoreCaseComparator implements Comparator<String>
      {
            public int compare(String strA, String strB) {
                  return strA.compareToIgnoreCase(strB);
            }
      }
}