Sorting Guava tables in descending order based on values

纵然是瞬间 提交于 2019-12-24 08:18:27

问题


I am planning to use guava tables for storing my values in the table format. I would like to know some function which performs the descending order sorting based on the value in the table ... Could you people throw some views about this. Thank you.


回答1:


Just like with maps, you should copy the cellSet(), sort the cells by the values, and then put that into an order-preserving 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();

This is more or less exactly the code you'd write to sort a map by values, anyway.



来源:https://stackoverflow.com/questions/11695949/sorting-guava-tables-in-descending-order-based-on-values

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