简体   繁体   中英

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?

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.

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