0

I have a nested Map being returned by the Guava Library's Table structure that is templated as follows:

Map<ComplexID1, Map<ComplexID2, MyObject>>

where ComplexID1 is my row key, ComplexID2 is my column key and MyObject holds my metadata. One of the attributes of my metadata is a JODA timestamp.

I need to sort this whole structure chronologically (or reverse chronologically) for display, newest objects created at the top, going backwards.

I was unable to find any information to sort this data structure. Could someone please provide some pointers?

Further, I tried to have the MyObject class extend Comparable and override compareTo on the JODA datetime object because I was trying to use Collections.Sort(). Unfortunately, that approach does not seem to work for me.

Kirby
  • 15,127
  • 10
  • 89
  • 104
adwaraki
  • 342
  • 1
  • 5
  • 14

2 Answers2

1

The solution pointed to below solves the problem perfectly. The code snippet is taken from there. Pasting it here for reference, credit to the original poster (question was under a different title, hence could not find it).

Sorting Guava tables in descending order based on values

Ordering<Table.Cell<String, FlowId, VersionData>> comparator =
    new Ordering<Table.Cell<String, FlowId, VersionData>>() {
        public int compare(
            Table.Cell<String, FlowId, VersionData> cell1,
            Table.Cell<String, FlowId, VersionData> cell2) {
                return cell1.getValue().compareTo(cell2.getValue());
            }
        };

ImmutableTable.Builder<String, FlowId, VersionData>
    sortedBuilder = ImmutableTable.builder();
    for (Table.Cell<String, FlowId, VersionData> cell :
           comparator.reverse().sortedCopy(tableBackedVersionStore.cellSet()))    
    {
        sortedBuilder.put(cell);
    }
    return sortedBuilder.build();
Community
  • 1
  • 1
adwaraki
  • 342
  • 1
  • 5
  • 14
0

Java8 solution:

List l = table.rowMap()
        .entrySet()
        .stream()
        .flatMap(row -> row.getValue().entrySet().stream()) //Flat row map
        .sorted((col1, col2) -> col2.getValue().compareTo(col1.getValue()))
        .collect(Collectors.toList());
卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130