Search code examples
javasortingdictionaryguavatreemap

Extract last x value from a treep map using guava


I have a TreeMap of Long and String and I have sorted it in reverse order of keys so that I can see latest timestamp at the top of the map. Bbelow is my code in which clientHistory will be sorted on keys in descending order.

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

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

Now for example, if clientHistory map has 500 elements in it. I want to extract last 400 clientId from that map into a List, basically first latest 100 client id I want to ignore.

I looked at this link and I tried out like this:

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

Th above line is giving me an error as The method descendingMap() is undefined for the type Map<Long,String>. What wrong I am doing?

Do I even need a TreeMap if I am using descendingMap feature?


Solution

  • You don't need guava for this. You can do it as follows:

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

    This will return the least recent values from your map, according to the keys, since your map is already ordering its entries in descending order.