Search code examples
javaguavatreemaptreeset

subset based on index from google guava TreeBasedTable


I have a TreeBasedTable<String,String,CustomType> structure from which I need to be able to get subsets based on start and end range indices, like fromindex to toindex. The cellSet method doesn't return a SortedSet. What would be the best approach for this?

I thought of doing Lists.newArrayList(structure.cellSet()).subList(start,end), but doesn't look like an efficient thing to do.


Solution

  • If startindex and endindex are integer positions, then your ArrayList implementation isn't actually that far off from the best that's feasible, though it'd be slightly more efficient to write

    FluentIterable.from(table.cellSet()).skip(fromIndex).limit(toIndex).toList()
    

    That implementation won't copy any more of the elements than it has to into the result list.

    Generally speaking, there's not an efficient way to do this for an arbitrary SortedSet, SortedMap, or pretty much any of the sorted data structures that come with Java.