Java - Store a list of person objects in SortedSet


Person class does not implement the Comparable interface.

The following code creates a SortedSet of persons using a Comparator that sorts the persons using their names:

SortedSet<Person> personsSortedByName = 
     new TreeSet<>(Comparator.comparing(Person::getName));

It uses a method reference to create a lambda expression for creating the Comparator object.

If you add two Person objects with the same name, the second one will be ignored.

personsSortedByName.add(new Person(1, "XML"));
personsSortedByName.add(new Person(2, "Json"));
// A duplicate Person. Will be ignored
personsSortedByName.add(new Person(3, "Json")); 

The following code uses a Comparator object to apply custom sorting in a SortedSet.

It uses two custom sortings for Person objects, one by id and one by name.


import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {
    // Create a sorted set sorted by id
    SortedSet<Person> personsById = new TreeSet<>(

    // Add some persons to the set
    personsById.add(new Person(1, "XML"));
    personsById.add(new Person(2, "Oracle"));
    personsById.add(new Person(3, "Eve"));
    personsById.add(new Person(4, "Json"));
    personsById.add(new Person(4, "Json")); // A duplicate Person

    // Print the set
    System.out.println("Persons by Id:");

    // Create a sorted set sorted by name
    SortedSet<Person> personsByName = new TreeSet<>(
    personsByName.add(new Person(1, "XML"));
    personsByName.add(new Person(2, "Oracle"));
    personsByName.add(new Person(3, "Eve"));
    personsByName.add(new Person(4, "Json"));
    personsByName.add(new Person(4, "Kip")); // Not a duplicate person

    System.out.println("Persons by Name: ");
  }//from w w  w.  j av a2 s.c o m

class Person {
  private int id;
  private String name;

  public Person(int id, String name) { = id; = name;

  public int getId() {
    return id;

  public void setId(int id) { = id;

  public String getName() {
    return name;

  public void setName(String name) { = name;

  public boolean equals(Object o) {
    if (!(o instanceof Person)) {
      return false;

    // id must be the same for two Persons to be equal
    Person p = (Person) o;
    if ( == p.getId()) {
      return true;

    return false;

  public int hashCode() {
    // A trivial implementation

  public String toString() {
    return "(" + id + ", " + name + ")";


Related Topic