Powered by Blogger.

How to sort an ArrayList

>> Tuesday, October 2, 2012

Sorting any ArrayList is pretty simple. Using Collections.sort( ) method we can sort the ArrayList. Collections class having all the static methods, we can use those methods directly along with the class name. These methods return the object as type Collection.

The important methods to synchronize the List, Set and Map as

synchronizedList(List<T> list)
synchronizedSet(Set<T> s)
synchronizedMap(Map<K,V> m) 

A simple program to sort an ArrayList
package blog.javabynataraj;

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

public class SortArraList {
 public static void main(String[] args) {
  
         List<String> mylist = new ArrayList<String>();
  
  mylist.add("Murali");
  mylist.add("Shakir");
  mylist.add("Aravind");
  mylist.add("Jayaprakash");
  mylist.add("Vivek");
  mylist.add("Sivaraj");
  
  System.out.println("***Before sorting the arrylist***");
  //iterate the list using for-each loop
  for(String names: mylist){
   System.out.println(names);
  }
  //Sort the ArrayList using sort() from Collections class
  Collections.sort(mylist);
  System.out.println("***After sorting the arraylist***");
  //iterate the list using for-each loop
  for(String names: mylist){
   System.out.println(names);
  }
 }

}

Here we are using Collections.sort(mylist) method to sort our list. Here the list is iterating using for-each loop. By this we can get the elements one by one in a new line instead to displaying as an ArrayList. To display entire arraylist just we can use
System.out.println(mylist);
it will displays the entire arrylist elements as
[Murali, Shakir, Aravind, Jayaprakash, Vivek, Sivaraj]
Collections class having a method to reverse the list is
Collections.sort(mylist);
 Collections.reverse(mylist);
 System.out.println(mylist);
The Output wil be:
[Vivek, Sivaraj, Shakir, Murali, Jayaprakash, Aravind]
if you want to iterate the arraylist without using Iterator loop you can as below given
Iterator<string> it = mylist.iterator();
     while(it.hasNext()){
       System.out.println(it.next());
     }
for this iteration the elements will be displayed in console as:

Murali
Shakir
Aravind
Jayaprakash
Vivek
Sivaraj

Output:

Output_Sorting an ArrayList_JavabynataraJ


Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.