Tag Archives: Collections.reverse(List)

How to Sort By Comparable Interface in Ascending and Descending Order : Java


As in previous post shown like wrapper of primitive type , String and Date classes having  implements in-built comparable interface which provide natural or chronological or alphabetical sorting of elements.

Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order

How to sort object by Comparator interface in ascending and descending order : JAVA

Java : Comparable Vs Comparator

What is Comparable Interface?

java.lang.Comparable  interface imposes a total natural ordering on the objects of each class that implements it.  it provide compareTo() method which compares the receiving object with the specified object and returns a negative integer, 0, or a positive integer depending on whether the receiving object is less than, equal to, or greater than the specified object. If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.

How to use Comparable Interface?

Below is syntax of compareTo method:

public interface Comparable {
    public int compareTo(T o);

}

compareTo() method compare current object (this)  fields values with passing object fields values and return negative integer, 0 or a positive integer and Collections.sort() method will sort based on this return value.

Lists (and arrays) of objects that implement this comparable interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this comparable interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

Example :

Below Employee class implements compareTo() method of  java.lang.Comparable  interface which is comparing firstName value with specified object firstName value. This  method return a integer value like (negative integer, 0 or positive integer) depend on compare result.

package sorting;

public class Employee implements Comparable{
private int id;
private String firtsName;
private String lastName;
private String designation;
private double salary;
private int age;

//Default Constructor
public Employee()
{

}

//Parametrize Constructor
public Employee(int id, String firtsName, String lastName, String designation, double salary, int age) {
	super();
	this.id = id;
	this.firtsName = firtsName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.age = age;
}

@Override
public int compareTo(Employee employee) {
	//sort by firstName
	return this.firtsName.compareTo(employee.firtsName);
}

public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getFirtsName() {
	return firtsName;
}
public void setFirtsName(String firtsName) {
	this.firtsName = firtsName;
}
public String getLastName() {
	return lastName;
}
public void setLastName(String lastName) {
	this.lastName = lastName;
}
public String getDesignation() {
	return designation;
}
public void setDesignation(String designation) {
	this.designation = designation;
}
public double getSalary() {
	return salary;
}
public void setSalary(double salary) {
	this.salary = salary;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}

@Override<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
public String toString() {
	return "Employee [id=" + id + ", firtsName=" + firtsName + ", lastName=" + lastName + ", designation=" + designation
			+ ", salary=" + salary + ", age=" + age + "]";
}

}

In below class sorting  Employee list objects by names in ascending order by Collections.sort(list). As shown above Employee Class implements  Comparable interface and it’s  compareTo() method  will sort elements in Ascending order by firstName on objects.

For Descending order used Collections.reverse(List) reverse method which will reverse list of sorted list.

 

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

public class SortComparable {

	public static void main(String[] args) {
		Employee [] empArr={
				new Employee(1,"Saurabh","Gupta","Sr Project Lead",60000,35),
				new Employee(2,"Gaurav","Gupta","Developer",50000,32),
				new Employee(3,"Shailesh","Nagar","Manager",100000,36),
				new Employee(4,"Ankur","Mehrotra","Lead",55000,30),
				new Employee(5,"Ranjith","Ranjan","Tester",35000,45),
				new Employee(6,"Ramesh","Bhardwaj","Support",25000,35)
				};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		//Print Assigned Values Before Sort;
		System.out.println("********Print Employee List Before Sort********");
		printArrayList(empList);

		//Sort List in Ascending order by collections api
		Collections.sort(empList);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		//Sort List in Descending order by collections api
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

	}

	private static void printArrayList(List empList)
	{
		for(Employee emp:empList)
		{
			System.out.println(emp);
		}
	}
}

 

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order


Collections framework provide Collections.sort(List) method which sort String elements in natural or chronological order or ascending order.

For descending order use Collections.reverse(List) method to reverse order of complete list elements.

Related Topics:

How to Sort By Comparable Interface in Ascending and Descending Order : Java

How to sort object by Comparator interface in ascending and descending order : JAVA

Java : Comparable Vs Comparator

Points to Remember:

  • Below are classes  implements  Comparable interface which provide a natural ordering for a class  sorted automatically.
  • If sorting a list of the elements which do not  implement Comparable , Collections.sort(list) method will throw ClassCastException. Similarly, Collections.sort(list, comparator ) will throw ClassCastException if you try to sort a list whose elements cannot be compared to another using Comparator.
                                 Classes Implementing Comparable
Class Natural Ordering
Byte Signed numerical
Character Unsigned numerical
Long Signed numerical
Integer Signed numerical
Short Signed numerical
Double Signed numerical
Float Signed numerical
BigInteger Signed numerical
BigDecimal Signed numerical
Boolean Boolean.FALSE < Boolean.TRUE
File System-dependent lexicographic on path name
String Lexicographic
Date Chronological
CollationKey Locale-specific lexicographic

Example :
In below example sorting list of names in ascending order by Collections.sort(list). As shown above String Class by default having Comparable interface which will sort elements in Ascending or Chronological order.

For Descending order used Collections.reverse(List) reverse method which will reverse list of sorted list.

package sorting;

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

public class SortData {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		//Print Assigned Values Before Sort;
		System.out.println("********Print Employee List Before Sort********");
		printArrayList(empList);

		//Sort List in Ascending order by collections api
		Collections.sort(empList);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		//Sort List in Descending order by collections api
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

	}

	private static void printArrayList(List empList)
	{
		for(String emp:empList)
		{
			System.out.println(emp);
		}
	}

}

Output:

********Print Employee List Before Sort********
Saurabh
Gaurav
Shailesh
Ankur
Ranjith
Ramesh

********Print Employee List in Ascending Order********
Ankur
Gaurav
Ramesh
Ranjith
Saurabh
Shailesh

********Print Employee List in Descending Order********
Shailesh
Saurabh
Ranjith
Ramesh
Gaurav
Ankur

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html