TreeSet

In this chapter you will learn:

  1. What is TreeSet
  2. How to create TreeSet
  3. Create a TreeSet with custom Comparator
  4. Create TreeSet from a List

TreeSet class

TreeSet extends AbstractSet and implements the NavigableSet interface. It creates a collection that uses a tree for storage. Objects are stored in sorted, ascending order.

TreeSet is a generic class that has this declaration:

class TreeSet<E>

E specifies the type of objects that the set will hold. A demonstration of a tree set with String elements sorted according to their natural ordering.

import java.util.Set;
import java.util.TreeSet;
/*from  j av a 2s. c  om*/
public class Main {
  public static void main(String[] args) {
    Set<String> ss = new TreeSet<String>();
    String[] fruits = { "apples", "pears", "grapes", "bananas", "kiwis" };
    for (String fruit : fruits){
      ss.add(fruit);
    }
    for (String s : ss){
      System.out.print(s + " ");
    }
  }
}

Output:

apples bananas grapes kiwis pears

Create TreeSet

  • TreeSet() Creates a tree set, sorted according to the natural ordering of its elements.
  • TreeSet(Collection<? extends E> c) Creates a tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
  • TreeSet(Comparator<? super E> comparator) Creates a tree set, sorted according to the specified comparator.
  • TreeSet(SortedSet<E> s) Creates a tree set from SortedSet.

The first form constructs an empty tree set that will be sorted in ascending order according to the natural order of its elements. The second form builds a tree set that contains the elements of c.

The third form constructs an empty tree set that will be sorted according to the comparator specified by comp. The fourth form builds a tree set that contains the elements of ss.

The following code creates a TreeSet from List

import java.util.Arrays;
import java.util.TreeSet;
//  j  ava2 s .co m
public class Main {
  public static void main(String args[]) throws Exception {

    String elements[] = { "java2s.com", "C", "D", "G", "F" };
    TreeSet<String> set = new TreeSet<String>(Arrays.asList(elements));

    System.out.println(set.headSet("D"));
    System.out.println(set.tailSet(""));
  }
}

Create a TreeSet with custom Comparator

The following code creates a Comparator first and then use it to create a TreeSet.

import java.util.Comparator;
import java.util.TreeSet;
//from j  a v  a2s.co m
class MyComparator implements Comparator<String> {
    public int compare(String a, String b) {
        String aStr, bStr;
        aStr = a;
        bStr = b;
        return bStr.compareTo(aStr);
    }
}

public class Main{
    public static void main(String args[]) {
        TreeSet<String> ts = new TreeSet<String>(new MyComparator());

        ts.add("java2s.com");
        ts.add("A");
        ts.add("B");
        ts.add("E");
        ts.add("F");
        ts.add("D");

        for (String element : ts)
            System.out.print(element + " ");

        System.out.println();
    }
}

The output:

Create TreeSet from a List

The following code creates a TreeSet from a List. And The list is created from an array.

import java.util.Arrays;
import java.util.TreeSet;
//from j a v a 2 s.c o  m
public class Main {
  public static void main(String args[]) throws Exception {

    String elements[] = { "java2s.com", "C", "D", "G", "F" };
    TreeSet<String> set = new TreeSet<String>(Arrays.asList(elements));

    System.out.println(set.headSet("D"));
    System.out.println(set.tailSet(""));
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to add elements to a TreeSet
Home » Java Tutorial » Collections

List interface
List add/insert elements
List clear/remove elements
List search
List element get and set
List and its Iterator
List size, empty
List conversion, to array
List to sublist
List comparison
ArrayList
ArrayList Creation
ArrayList add/insert
ArrayList get/set element
ArrayList clear/remove
ArrayList search
ArrayList copy and shallow copy
ArrayList size, trim to size and capacity
ArrayList to array
LinkedList class
LinkedList creation
LinkedList add/insert elements
LinkedList get elements
LinkedList search
LinkeList replace/set elements
LinkedList remove element
LinkedList copy
LinkedList iterator
LinkedList peek element
LinkedList pop/push element
LinkedList conversion
Map interface
Map element adding
Map.Entry class
Map key
Map value
Map key/value search
Map delete/remove
Map comparison
HashMap Class
HashMap search
HashMap clone
TreeMap
TreeMap key
TreeMap head sub map
TreeMap tail sub map
TreeMap sub map
NavigableMap
NavigableMap key
NavigableMap key-value pair
LinkedHashMap Class
IdentityHashMap
SortedMap
HashSet
HashSet element adding
HashSet element removing and clearing
HashSet clone
HashSet iterator
HashSet properties
TreeSet
TreeSet elements adding
TreeSet subSet
NavigableSet
LinkedHashSet
Iterator
ListIterator
List filling
List reversing
List rotating and shuffling
List sorting
List element swap
List element replacing
List copy
List binary search
Collection unmodifiable
Collection synchronized
Collection singleton
Collection max/min value
Empty Collections
Comparator
Comparable
Enumeration
EnumSet
EnumMap Class
PriorityQueue