Can TreeMap be used to retrieve all key/value pairs above a given key value?

I have a piece of code that maintains a map of revisions done to samples with a given ID:

private Map<Long, SampleId> sampleRevisionMap = new HashMap<>();

While maintaining this, other threads can call in to get all changes made since the given revision number. To find the relevant IDs I do

public Set<SampleId> getRevisionIDs(long clientRevision) {
    return sampleRevisionMap.entrySet().stream()
                .filter(k -> k.getKey() > clientRevision)
                .map(entry -> entry.getValue())
                .collect(Collectors.toSet());
}            

In short, give me all values with key above a threshold.

is there a better way to do this employing an ordered map, i.e. java.utils.TreeMap?

Answer

Yes, you can do it by calling tailMap:

public Collection<SampleId> getRevisionIDs(long clientRevision) {
    return sampleRevisionMap.tailMap(clientRevision).values();
}    

The above includes the value mapped to clientRevision as well. If you want everything above it, use clientRevision+1 instead.

Leave a Reply

Your email address will not be published. Required fields are marked *