Site icon Narayana Tutorial

Comparator List Sorting

Comparator List Sorting

In this example showing how to sort objects in the List by using a comparator. Primitive Type List, Wrapper Classes Type List can be sorted by using the Collection.sort(), but Object type List can’t be sorted. To achieve this we can use either Comparator and Comparable.

 

Comparator

A Comparator interface is used to order the objects of a specific class. This interface is found in java.util package. It contains two methods;

DataVO.java

package com.narayanatutorial.JavaComparatorSorting;

public class DataVO {

	private String startdate;
	private String name;
	
	public String getStartdate() {
		return startdate;
	}
	public void setStartdate(String startdate) {
		this.startdate = startdate;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

 

ComparatorSortingByName.java

package com.narayanatutorial.JavaComparatorSorting;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

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

		DataVO vo = null;
		List<DataVO> list = new ArrayList<DataVO>();
		vo = new DataVO();
		vo.setName("Tutorial");
		vo.setStartdate("2020-01-17");
		list.add(vo);

		vo = new DataVO();
		vo.setName("Narayana");
		vo.setStartdate("2020-01-19");
		list.add(vo);

		vo = new DataVO();
		vo.setName("Swamy");
		vo.setStartdate("2020-01-18");
		list.add(vo);

		System.out.println("****Before Sorting****");
		list.stream().forEach(datavo -> System.out.println(datavo.getName()));

		// Ascending order
		Collections.sort(list, new Comparator<DataVO>() {
			public int compare(DataVO s1, DataVO s2) {
				return (s1.getName().compareTo(s2.getName()));
			}
		});

		System.out.println("****Asecnding After Sorting****");
		list.stream().forEach(datavo -> System.out.println(datavo.getName()));

		// Descending order
		Collections.sort(list, new Comparator<DataVO>() {
			public int compare(DataVO s1, DataVO s2) {
				return (s2.getName().compareTo(s1.getName()));
			}
		});

		System.out.println("****Desecnding After Sorting****");
		list.stream().forEach(datavo -> System.out.println(datavo.getName()));

	}
}

 

Output

****Before Sorting****
Tutorial
Narayana
Swamy
****Asecnding After Sorting****
Narayana
Swamy
Tutorial
****Desecnding After Sorting****
Tutorial
Swamy
Narayana

 

Get full source code from Git.