Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Hashmap: get all keys greater than X value

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

OUTPUT

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?

like image 306
ealeon Avatar asked Feb 19 '19 18:02

ealeon


2 Answers

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.

like image 63
MC Emperor Avatar answered Sep 20 '22 23:09

MC Emperor


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

like image 22
sims_gfl Avatar answered Sep 18 '22 23:09

sims_gfl