Natural Ordering
Google Guava is a java library with lot of utilities and reusable components.
This requires the library guava-10.0.jar to be in classpath.
The following example shows using Ordering.natural() API.
package com.bethecoder.tutorials.guava.collection_tests;
import java.util.List;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
public class OrderingNaturalTest {
/**
* @param args
*/
public static void main ( String [] args ) {
List<Integer> intList = Lists.newArrayList ( 5 , 7 , 6 , 1 , 2 , 9 , 8 , 4 , 3 ) ;
List<Integer> sortedCopy = Ordering.natural () .sortedCopy ( intList ) ;
System.out.println ( "Original List : " + intList ) ;
System.out.println ( "Sorted copy : " + sortedCopy ) ;
List<String> strList = Lists.newArrayList ( "DD" , "BB" , "CC" , "AA" ) ;
List<String> strSortedCopy = Ordering.natural () .sortedCopy ( strList ) ;
System.out.println ( "Original List : " + strList ) ;
System.out.println ( "Sorted copy : " + strSortedCopy ) ;
}
}
It gives the following output,
Original List : [5, 7, 6, 1, 2, 9, 8, 4, 3]
Sorted copy : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Original List : [DD, BB, CC, AA]
Sorted copy : [AA, BB, CC, DD]