Sort user defined objects in TreeSet (using Comparable)

  • Elements in TreeSet are ordered using natural order or Comparator/Comparable interface.
  • In case of user defined objects or POJO, POJO needs to implement Comparable interface to sort objects.
  • TreeSet will invoke the compareTo method of POJO, to sort POJOs (contained in TreeSet)
  • We have already discussed to sort user defined objects using Comparator interface.

Example – Sort Car POJO contained in TreeSet

TreeSet is containing Car objects. Car class has following attributes.

  • public String model
  • public String owner
  • public String registerCity
  • public LocalDate serviceDate
  • Car class will implements Comparable interface.
    • Car class will override compareTo method (to achieve sorting).
    • Car objects will be sorted by model.

Program – Sort user defined objects contained in TreeSet

package org.learn.collection.set.tset;

import java.time.LocalDate;
import java.time.Month;
import java.util.TreeSet;

class Car implements Comparable<Car>{
	public String model;	
	public String owner;
	public String registerCity;
	public LocalDate serviceDate;

	public Car(String model,String owner, String registerCity, LocalDate serviceDate) {
		this.model = model;
		this.serviceDate = serviceDate;
		this.owner = owner;
		this.registerCity = registerCity;
	}

	public String toString() {
		 return String.format("\n[Model:%s,Owner:%s,registeredCity:%s,ServiceDate:%s]", 
				 model,owner,registerCity,serviceDate.toString());
	 }

	@Override
	public int compareTo(Car car) {
		return this.model.compareTo(car.model);
	}
}

public class DemoTreeSetComparable {

	public static void main(String[] args) {
		TreeSet<Car> carList = new TreeSet<Car>();
		carList.add(new Car("S-Class", "Guzan", "NewYork", LocalDate.of(2014, Month.AUGUST, 01)));
		carList.add(new Car("C-Class", "Bedoya", "California", LocalDate.of(2009, Month.DECEMBER, 05)));
		carList.add(new Car("A-Class", "Cameron", "Illinois", LocalDate.of(2014, Month.JULY, 25)));
		carList.add(new Car("SL-Class", "Johnson", "Kansas" ,LocalDate.of(2011, Month.DECEMBER, 10)));
		System.out.println("Sorted car objects by Model:\n"+ carList);				
	}
}

Output – Sort user defined objects contained in TreeSet

Sorted car objects by Model:
[
[Model:A-Class,Owner:Cameron,registeredCity:Illinois,ServiceDate:2014-07-25], 
[Model:C-Class,Owner:Bedoya,registeredCity:California,ServiceDate:2009-12-05], 
[Model:S-Class,Owner:Guzan,registeredCity:NewYork,ServiceDate:2014-08-01], 
[Model:SL-Class,Owner:Johnson,registeredCity:Kansas,ServiceDate:2011-12-10]]
Scroll to Top