Java Hashmap: get all keys greater than X value

Streams, yes. Use

expirationMap.entrySet().stream()
    .filter(entry -> entry.getValue() > 3L)
    .map(Entry::getKey)
    .collect(Collectors.toList());

to get a list of the keys.

We need to stream over the map entries rather than the values or keys only, because we need to compare the one (the value) and return the other (the key). Okay, one need not, as nullpointed out in the comments.

The filter method gets the value and compares it to 3, discarding elements not greater than 3; and then we map the entries to their values using the map method. Finally, we collect the result into a List.


A slightly different variation using just set and key lookup:

Set<String> greppedKeys = expirationMap.keySet().stream() // keyset only
        .filter(key -> expirationMap.get(key) > 3L) // X here being 3L
        .collect(Collectors.toSet()); // all keys would be unique anyway

See below for another readable approach.

expirationMap.forEach((key, value) -> {
     if (value > x) {
         System.out.println(format("key: %s, value: %s", key, value));
     }
});

The .forEach part will iterate over the map's entrySet() and extract each entry's key and value respectively onto (key, value).