Reputation: 905
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.
Upvotes: 1
Views: 2889
Reputation: 198103
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.
Upvotes: 6