Java - Collection Framework SortedSet Subsets

Introduction

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.

Demo

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<>();
    names.add("XML");
    names.add("Oracle");
    names.add("Eve");
    names.add("Json");

    // 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.  j a va 2  s .  c o  m*/

    // 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);
  }
}

Result

Related Topic