Java Reference
In-Depth Information
The code uses a method reference to create a lambda expression for creating the Comparator object. Please refer
to Chapter 5 for more details on the lambda expressions and method references.
If you add two Person objects to the personsSortedByName sorted set with the same name, the second one will be
ignored because the supplied Comparator compares names of two Person objects for equality.
personsSortedByName.add(new Person(1, "John"));
personsSortedByName.add(new Person(2, "Donna"));
personsSortedByName.add(new Person(3, "Donna")); // A duplicate Person. Will be ignored
Listing 12-10 demonstrates how to use 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 . The output shows that one SortedSet is sorted by id
and another by name .
Listing 12-10. Using Custom Sorting in a SortedSet
// SortedSetComparatorTest.java
package com.jdojo.collections;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedSetComparatorTest {
public static void main(String[] args) {
// Create a sorted set sorted by id
SortedSet<Person> personsById =
new TreeSet<>(Comparator.comparing(Person::getId));
// Add soem persons to the set
personsById.add(new Person(1, "John"));
personsById.add(new Person(2, "Adam"));
personsById.add(new Person(3, "Eve"));
personsById.add(new Person(4, "Donna"));
personsById.add(new Person(4, "Donna")); // 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, "John"));
personsByName.add(new Person(2, "Adam"));
personsByName.add(new Person(3, "Eve"));
personsByName.add(new Person(4, "Donna"));
personsByName.add(new Person(4, "Kip")); // Not a duplicate person
System.out.println("Persons by Name: ");
personsByName.forEach(System.out::println);
}
}
 
Search WWH ::




Custom Search