tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Java > Collections > Array Sort

Array Sort 

The following code shows how to sort arrays using Arrays API.

File Name  :  
com/bethecoder/tutorials/collections/ArraySortTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.collections;

import java.util.Arrays;
import java.util.Comparator;

public class ArraySortTest {

  public static void main(String[] args) {
    
     String [] strings = "ONE""TWO""THREE""FOUR""FIVE""SIX" };
    
     //Natural sort
     Arrays.sort(strings);
     
     for (String str : strings) {
       System.out.println(str);
     }
     
     System.out.println("----------------");
     
     //Reverse sort
     Arrays.sort(strings, new Comparator<String>() {

      public int compare(String first, String second) {        
        return -first.compareTo(second);
        //or
        //return second.compareTo(first);
      }
       
     });
     
     for (String str : strings) {
       System.out.println(str);
     }
  }
}
   

It gives the following output,
FIVE
FOUR
ONE
SIX
THREE
TWO
----------------
TWO
THREE
SIX
ONE
FOUR
FIVE


                    Print

   



Books Recommendation

 
 
bl  br