Tutorials

Collection Programs


ArrayList Sorting


In this chapter, we will 

  • We will create an arraylist
  • We will add elements to arraylist
  • Sort the elements of the arraylist

See the code snippet given below



package javaRadarArrayList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class SortArrayList {

       public static void main(String[] args) {

           //create Array List
             ArrayList javaRadarList = new ArrayList();

           //Add elements to ArrayList
             javaRadarList.add("Java");
             javaRadarList.add("Jquery");
             javaRadarList.add("Spring");
             javaRadarList.add("Hibernate");
             javaRadarList.add("EJB");

             System.out.println("Before sorting: " +javaRadarList);

              Collections.sort(javaRadarList); //sorting list element
              
              //use iterator to traverse list
              Iterator itrAfterSort = javaRadarList.iterator();

              System.out.println("After Sorting:");

              while(itrAfterSort.hasNext()){

               String token = itrAfterSort.next();
               System.out.println(token);

              }

       }

}

OUTPUT

Before sorting: [Java, Jquery, Spring, Hibernate, EJB]
After Sorting:
EJB
Hibernate
Java
Jquery
Spring
 

 

 



Please Share this page
Views : 30