Java - Collection Framework SortedSet Subsets


You can get subsets of SortedSet by value range.

To get a subset of the SortedSet, use its subSet(E fromElement, E toElement) method to get the elements between fromElement (inclusive) and toElement (exclusive).

The following code uses some of the methods of the SortedSet interface to get a subset of its elements.


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

public class Main {
  public static void main(String[] args) {
    // Create a sorted set of names
    SortedSet<String> names = new TreeSet<>();

    // Print the sorted set
    System.out.println("Sorted Set: " + names);

    // Print the first and last elements in the sorted set
    System.out.println("First: " + names.first());
    System.out.println("Last: " + names.last());

    SortedSet<String> ssBeforeJson = names.headSet("Json");
    System.out.println("Head Set Before Json: " + ssBeforeJson);

    SortedSet<String> ssBetwenJsonAndXML = names.subSet("Json", "XML");
    System.out.println("Subset between Json and XML (exclusive): "
        + ssBetwenJsonAndXML);/*from ww w .ja v  a  2 s .  c  om*/

    // Note the trick "XML" + "\0" to include "XML" in the subset
    SortedSet<String> ssBetwenJsonAndXML2 = names.subSet("Json", "XML" + "\0");
    System.out.println("Subset between Json and XML (Inclusive): "
        + ssBetwenJsonAndXML2);

    SortedSet<String> ssJsonAndAfter = names.tailSet("Json");
    System.out.println("Subset from Json onwards: " + ssJsonAndAfter);


Related Topic