Search code examples
javadata-structurestreetreemaptreeset

How do I return a TreeSet of the values contained in a TreeMap?


I am trying to get a set of all the values for keys in a TreeMap that are greater than some value, key.

Code attempt below:

TreeSet<E> set = (TreeSet<E>)tMap.tailMap(key, false).values();

Is there a way to do this in Java?

Thanks!!


Solution

  • values() returns a Collection, so you can always feed that Collection to TreeSet constructor (assuming your E class implements Comparable<E>):

    TreeSet<E> set = new TreeSet<E>(tMap.tailMap(key, false).values());
    

    If you wish the TreeSet to use some custom Comparator instead of natural ordering, you can write:

    TreeSet<E> set = new TreeSet<E> (yourComparator);
    set.addAll(tMap.tailMap(key, false).values());