Sunday, February 8, 2015

Sorting strings using java Collections

In this tutorial Lets see how to sort collection of Strings in alphabetical order in a very simple way. We use java Collections for that.

Here is the coding example.

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

public class CollectionSort {
 public static void main (String[] args){ 

  List<String> names = new ArrayList<String>();  

  names.add("Nimal");
  names.add("Sunil");
  names.add("Tharaka");
  names.add("Isuru");
  names.add("Suresh");
  names.add("Anuradha");
  names.add("Thilak");  

  Collections.sort(names);  

  int i=1;
  for(String name:names)
   System.out.println("item "+i+++" "+name);
 }
}

Output for this code will be like this.


item 1 Anuradha
item 2 Isuru
item 3 Nimal
item 4 Sunil
item 5 Suresh
item 6 Tharaka
item 7 Thilak


2 comments:

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...