Sorting Guava table on values

不羁的心 提交于 2020-01-16 06:34:44

问题


Is there any possible way to do that? The expecting effect would be that rowMap and columnMap entry values would be sorted by value.

The problem is that I cannot create a comparator without the underlying maps in Table.

Table table = TreeBasedTable.create(?,?);

Map<String, Map<String, String>> rowMap = table.rowMap();
Map<String, String> thisMapShouldBeSortedByValues = rowMap.get(smth);

Map<String, Map<String, String>> columnMap = table.columnMap();
Map<String, String> thisMapShouldBeSortedByValues = columnMap.get(smth);

Now I always have to sort rowMap and columnMap afterwards and allocate new TreeMaps on that.


回答1:


First of all, I am assuming that by thisMapShouldBeSortedByValues, you mean thisMapShouldBeSortedByKeys

TreeBasedTable extends RowSortedTable, so the table is only sorted by it's rows, not its columns. Calling table.columnMap() gives you an unordered Map<C, Map<R, V>.

Since it is sorted by rows, the table.rowMap returns a SortedMap<R, Map<C, V>>. So the map is sorted on it's row keys, but the Map<C, V> value is an unsorted map, hence why calls to rowMap.get() returns an unordered map.

The SortedMap you are trying to get from calling table.rowMap(), and then rowMap.get(), can be obtained by instead calling table.rowKeySet() and table.row(R rowKey) like so (You build the map you originally wanted to get by calling table.rowMap():

ImmutableSortedMap.Builder<String, SortedMap<String, String>> builder = ImmutableSortedMap.builder();

for (String rowKey : table.rowKeySet()){
     builder.put(rowKey, table.row(rowKey)) ;
}

 SortedMap<String, <SortedMap<String, String>> thisMapIsSortedByKeys = builder.build();


来源:https://stackoverflow.com/questions/11256840/sorting-guava-table-on-values

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