Tutorials

Collection Programs


ArrayList Binary Search


In this chapter, we will

  • Create arraylist
  • Add elements to arraylist
  • Sort the current arraylist
  • Travese the sorted list using iterator
  • Perform binary search operation on arraylist for any key.

Binary Search operation can be performed only on sorted list. 

See the code snippet 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 after sorting
           Iterator itrAfterSort = javaRadarList.iterator();

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

            while(itrAfterSort.hasNext()){

            String token = itrAfterSort.next();

               System.out.println(token);

            }

            //Binary Search can be performed on Sorted List
            int i=Collections.binarySearch(javaRadarList, "Spring");

            System.out.println("Given Key is present at index :"+ i +" on sorted list");

     }

}

OUTPUT:

Before sorting: [Java, Jquery, Spring, Hibernate, EJB]
After Sorting:
EJB
Hibernate
Java
Jquery
Spring
Given Key is present at index :4 on sorted list
 

 

 



Please Share this page
Views : 35