tttppp
tttppp

Reputation: 8193

How can I get an exclusive tailset of a SortedSet?

I want to get an exclusive tail set of a SortedSet. The shortest method I can come up with is:

private void exclusiveTailSet(SortedSet<String> s, String start) {
    System.out.println(s); // [Five, Four, One, Six, Start, Three, Two]
    SortedSet<String> t = s.tailSet(start);
    System.out.println(t); // [Start, Three, Two]
    Iterator<String> i = t.iterator();
    i.next();
    SortedSet<String> u = t.tailSet(i.next());
    System.out.println(u); // [Three, Two]
}

The javadoc for tailSet suggests asking for the subset starting from the next element in the domain (i.e. for Strings calling s.tailSet(start+"\0");), however I'm actually working with objects such that it would be much more of an overhead to create it.

What is an efficient and clean general method to create an exclusive tail set?

Upvotes: 3

Views: 2250

Answers (4)

acridity
acridity

Reputation: 31

Guava version 11:

   SortedSet exclusiveTailSet = Sets.filter(eSortedSet, Ranges.greaterThan(start));

p.s. There is also a hack for SortedSet in case you couldn't use NavigableSet. The solution is to add for the search pattern a special symbol (start+"\0"). And this addition symbol will change the hashCode and thus the default tailset implementation of a SortedSet will work fine:

 SortedSet<String> t = s.tailSet(start+"\0"); 

It will be an equivalent of java.util.TreeSet#tailSet(E fromElement, boolean inclusive) with false value in a second parameter.


God bless that the last com.google.common.collect.ImmutableSortedSet (since version 12) has an implementation of NavigableSet also.

Upvotes: -1

Kent
Kent

Reputation: 195169

is this helpful? (I just copy and paste your codes in question, and did some change:

private void exclusiveTailSet(SortedSet<String> s, String start) {

    SortedSet<String> t = s.tailSet(start);


    t.remove(t.first());


}

and if you have "start" element as parameter, it would also be

t.remove(start) ;

Upvotes: 0

aioobe
aioobe

Reputation: 421080

I don't see any better method than the one you describe.

You can make it slightly more general though, by making it a generic method:

public static <T> SortedSet<T> exclusiveTailSet(SortedSet<T> ts, T elem) {
    Iterator<T> iter = ts.tailSet(elem).iterator();
    iter.next();
    return ts.tailSet(iter.next());
}

Upvotes: 3

Mechkov
Mechkov

Reputation: 4324

NavigableSet interface is a subimplementation of the SortedSet. If i understand your question correctly you can use NavigableSet's tailset method, which has the ability to be either inclusive or exclusive, depending on what boolean you provide.

 NavigableSet<E>    tailSet(E fromElement, boolean inclusive)
      Returns a view of the portion of this set whose elements are greater than (or    equal     to, if inclusive is true) fromElement.

http://download.oracle.com/javase/6/docs/api/java/util/NavigableSet.html

Upvotes: 5

Related Questions