简体   繁体   中英

Timestamp based sorting for a nested Map

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.

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();

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM