Java Sort a Guava TreeBasedTable

被刻印的时光 ゝ 提交于 2019-11-28 08:47:54

问题


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?


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/7001582/java-sort-a-guava-treebasedtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!