[英]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: 我有一个Guava库的Table结构返回的嵌套Map
,该结构的模板如下:
Map<ComplexID1, Map<ComplexID2, MyObject>>
where ComplexID1
is my row key, ComplexID2
is my column key and MyObject
holds my metadata. 其中ComplexID1
是我的行键, ComplexID2
是我的列键, MyObject
保存我的元数据。 One of the attributes of my metadata is a JODA timestamp. 我的元数据的属性之一是JODA时间戳。
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()
. 此外,由于尝试使用Collections.Sort()
,我尝试使MyObject
类扩展Comparable
并在JODA datetime对象上重写compareTo
。 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 基于值对Guava表进行降序排序
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: Java8解决方案:
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.