Java Sort a Guava TreeBasedTable
I have a TreeBasedTable
object from Guava (Gooogle Collections). It is in the form of TreeBasedTable<k1, k2, v>
. k1
and k2
implement Comparable
. Now when I display the table, I want the user to be able to sort it different ways to change the order of the values.
The approach I tried was to iterate over the table, and for each value, change a variable that's used in the Compare method. The trouble is it gets through the loop once, and then returns a NullPointerException
, which I think I've narrowed down to trying to change the order whilst iterating over it (rookie mistake, I know).
So I was wondering, what would be a good way to reorder this table?
How about if you just create a new TreeBasedTable, created with a different comparator object, and then copy the original into it via public putAll method? The put for each element will take log(N), so total time should be N log(n), which is about the time I would expect for a re-sort to take.
You should recreate TreeBasedTable and supply to it another Comparator. Please see the guava documentation. Also note, that this internally uses trees that must be sorted with proper comparator (when you are building the tree, comparator is known, so that tree is built in specific way). Supplying other comparator would result in building new tree. If this isn't desired behaviour for you, you should be thinking about using other data structure.
Use TreeBasedTable.create(TreeBasedTable<R, C, ? extends V>)
to create a new one from the previous after you have modified your comparator by switching one of his flags
精彩评论