Sunday, 22 July 2012

ArrayList Sorting Example


ArrayList Sorting Example


package com.demo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortArrayList {

 public static void main(String[] args) {

   //create an ArrayList object
   List<String> arrayList = new ArrayList<String>();

   //Add elements to Arraylist
/* arrayList.add("A");
   arrayList.add("B");
   arrayList.add("C");
   arrayList.add("D");
   arrayList.add("E");*/

   arrayList.add("1");
   arrayList.add("5");
   arrayList.add("8");
   arrayList.add("2");
   arrayList.add("0");

   /*
     To get comparator that imposes reverse order on a Collection use
     static Comparator reverseOrder() method of Collections class
   */
   Collections.sort(arrayList);

    System.out.println("sorted list is "+arrayList);
 

   Comparator comparator = Collections.reverseOrder();

   System.out.println("Before sorting ArrayList in descending order : "
                                                             + arrayList);

   /*
     To sort an ArrayList using comparator use,
     static void sort(List list, Comparator c) method of Collections class.
   */

   Collections.sort(arrayList,comparator);
   System.out.println("After sorting ArrayList in descending order : "
                                                             + arrayList);

 }
}

No comments:

Post a Comment

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...