使用番石榴从 treep 地图中提取最后一个 x 值

Extract last x value from a treep map using guava

我有一个由 Long 和 String 组成的 TreeMap,我已按键的相反顺序对它进行排序,以便我可以在地图顶部看到最新的时间戳。 Bbelow 是我的代码,其中 clientHistory 将按键降序排序。

Map<Long, String> clientHistory = new TreeMap<>(Collections.reverseOrder());

for(...) {
    // ... some code
    clientHistory.put(data.getModifiedTime(), clientId);
}

现在例如,如果 clientHistory 地图中有 500 个元素。我想从该映射中提取最后 400 个 clientId 到一个列表中,基本上是我想忽略的第一个最新的 100 个客户端 ID。

我看了这个 link 我试了这样:

Map<Long, String> clientHistory = new TreeMap<>(Collections.reverseOrder());

for(...) {
    // ... some code
    clientHistory.put(data.getModifiedTime(), clientId);
}

List<String> lastClientIdValues = Lists.newArrayList(Iterables.limit(clientHistory.descendingMap().values(), clientHistory.size() - 100));

上面的行给我一个错误 The method descendingMap() is undefined for the type Map<Long,String>。我做错了什么?

如果我使用 descendingMap 功能,还需要 TreeMap 吗?

你不需要番石榴。您可以按如下方式进行:

int size = yourMap.size();
List<String> leastRecent = new ArrayList<>(
    yourMap.values()).subList(size - 400, size);

这将根据键 return 地图中最近的值,因为您的地图已经按降序对其条目进行排序。