skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Showing posts with label Java Collection Example. Show all posts
Showing posts with label Java Collection Example. Show all posts
Saturday, October 13, 2012

Sorting an ArrayList using Collections sort method

Posted by Raju Gupta at 6:00 PM – 0 comments
 
This code can help in sorting an ArrayList using Collections.sort() method. Here in the example, we have passed string values & these are sorted alphabetically in ascending & descending order.

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collections; 
import java.util.List;   
public class ArrayListSortExample 
{   
  public static void main(String[] args) 
{        
 
/*           Create a collections of colours          */   
   List colours = new ArrayList();       
  colours.add("red");        
 colours.add("green");        
 colours.add("blue");       
colours.add("yellow");      
   colours.add("cyan");       
  colours.add("white");       
  colours.add("black");     


Collections.sort(colours);        
 System.out.println(Arrays.toString(colours.toArray()));       
    Collections.sort(colours, Collections.reverseOrder());     
    System.out.println(Arrays.toString(colours.toArray()));   
   } 
} 

/*
Output : 

[black, blue, cyan, green, red, white, yellow]
[yellow, white, red, green, cyan, blue, black]
*/

[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger