基于值按降序对Guava表进行排序

Nan*_*mar 1 java hashmap guava

我打算使用guava表以表格格式存储我的值.我想知道一些函数,它根据表中的值执行降序排序...你能否就此发表一些观点.谢谢.

Lou*_*man 6

就像地图一样,您应该复制cellSet(),按值对单元格进行排序,然后将其放入订单保留中ImmutableTable.

Ordering<Table.Cell<String, String, Integer>> comparator =
  new Ordering<Table.Cell<String, String, Integer>>() {
    public int compare(
        Table.Cell<String, String, Integer> cell1, 
        Table.Cell<String, String, Integer> cell2) {
      return cell1.getValue().compareTo(cell2.getValue());
  }
};
// That orders cells in increasing order of value, but we want decreasing order...
ImmutableTable.Builder<String, String, Integer>
    sortedBuilder = ImmutableTable.builder(); // preserves insertion order
for (Table.Cell<String, String, Integer> cell :
    comparator.reverse().sortedCopy(table.cellSet())) {
  sortedBuilder.put(cell);
}
return sortedBuilder.build();
Run Code Online (Sandbox Code Playgroud)

无论如何,这或多或少都是您用于按值对地图进行排序的代码.