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.
Asked
Active
Viewed 2,837 times
1
-
possible duplicate of [Java Sort a Guava TreeBasedTable](http://stackoverflow.com/questions/7001582/java-sort-a-guava-treebasedtable) – Francisco Spaeth Jul 27 '12 at 21:44
1 Answers
6
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.

WhiteFang34
- 70,765
- 18
- 106
- 111

Louis Wasserman
- 191,574
- 25
- 345
- 413
-
Thank you for your answer.. If possible could u pls give a glimpse of this or a link reference – NandaKumar Jul 30 '12 at 05:07