Java Collection Sort Example


A simple example using Collection to sort list into ascending and descending order.

-------------------------------CODE -------------------------------


import java.util.List;
import java.util.Arrays;
import java.util.Collections;

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

//CREATE ARRAY AND POPULATE IT
String names[] ={"Mark","Paul","James","Clair"};

//CREATE LINKEDLIST AND POPULATE IT WITH ABOVE ARRAY
List<String> nameList = Arrays.asList(names);

//DISPLAY LIST BEFORE SORT
System.out.printf("Before Sort :%s\n\n",nameList);

//SORT LIST INTO Alphabetical order
Collections.sort(nameList);
System.out.printf("After Sort : %s\n\n",nameList);


//SORT LIST INTO Reverse order
Collections.sort(nameList,Collections.reverseOrder());
System.out.printf("After Reverse Sort : %s",nameList);
}
}

---------------------OUTPUT ----------------------------


Before Sort :[Mark, Paul, James, Clair]

After Sort : [Clair, James, Mark, Paul]

After Reverse Sort : [Paul, Mark, James, Clair]


No comments:

Post a Comment