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?
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
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With