Java Programing laungage

java.util Projects

java.util Project 1

Sorting of Collection element

In This programming tutorials, we are going to sorting elements of a Collection. we can see how to sort all elements of a Collection in ascending or descending order. In this tutorials, the given Example sorts all the elements of a Collection in ascending order. If your text starts with the Upper case letter then the text comes first that mean the uppercase letter is less priority than lowercase letter.

Previous Home Next

Code Description: In This program creates an string type array in which we are insert some text as input from the user for the created array. Array with elements are assigned to the List (Collection) and then all the elements of the list are arranged in the ascending order.

Collections.sort(list): This method is used to sorts all the elements of the specified Collection. List name of the element in which elements have to be store is passed through the method as a parameter. This method sorts elements in ascending order by default.

Example


package r4r;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class sortelementcollection {
public static void main(String[] args) throws IOException{
int n = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many elements want to enter: ");
try{
n = Integer.parseInt(br.readLine());
}



catch(NumberFormatException ne){
System.out.println(ne.getMessage() + " is not a right entry.");
System.out.println("Enter a numeric value only.");
System.exit(1);
}
String[] string = new String[n];
System.out.println("Please enter some String : ");
for(int i = 0; i < n; i++){
	string[i] = br.readLine();
}
List<String> lst = Arrays.asList(string);
Collections.sort(lst);
System.out.print("Elements of the list in sorted order : " + lst);
}
}

Previous Home Next