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<>( Comparator.comparing(Person::getId)); // 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:"); personsById.forEach(System.out::println); // Create a sorted set sorted by name SortedSet<Person> personsByName = new TreeSet<>( Comparator.comparing(Person::getName)); 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: "); personsByName.forEach(System.out::println); }/*from w ww. j a v a2s. c o m*/ } class Person { private int id; private String name; public Person(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override 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 (this.id == p.getId()) { return true; } return false; } @Override public int hashCode() { // A trivial implementation return this.id; } @Override public String toString() { return "(" + id + ", " + name + ")"; } }