Java Hashmap: get all keys greater than X value

  • A+
 import java.util.*;  import static java.lang.String.format;   public class Dumpground {       private static final String[] fruits = new String[]{"apples", "bananas", "grapes", "oranges", "watermelons", "kiwis"};      static Map<String, Long> expirationMap;       public static void main(String[] args) {          long expiration = 1L;          expirationMap = new HashMap<>();          for (String fruit : values()){              expirationMap.put(fruit, expiration);              expiration++;          }          for (Map.Entry<String, Long> item : expirationMap.entrySet()) {                String key = item.getKey();                Long value = item.getValue();                System.out.println(format("key: %s, value: %s", key, value));            }        }       public static String[] values() {return fruits;}  } 


key: oranges, value: 4 key: watermelons, value: 5 key: kiwis, value: 6 key: bananas, value: 2 key: apples, value: 1 key: grapes, value: 3 

I am trying to find a clever ways to grep all keys where its values are greater than X

for example, if X == 3, it should return oranges, and watermelons and kiwis

the obvious way is just iterate through map and compare the value, but is there easy, concise way to do it?


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: