Java Hashmap:获取所有大于 X 值的键


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

我正在尝试找到一种聪明的方法来 grep 其值大于 X 的所有键

例如,如果 X == 3,它应该返回橙子、西瓜和猕猴桃

显而易见的方法只是遍历 map 并比较值,但是有没有简单、简洁的方法可以做到这一点?

流,是的。用

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

以获取密钥列表。

我们需要流式传输映射条目,而不仅仅是值或键,因为我们需要比较一个(值)并返回另一个(键)。好的,正如评论中指出的那样,不需要。

filter方法获取值并将其与 3 进行比较,丢弃不大于 3 的元素;然后我们使用map方法将条目映射到它们的值。最后,我们将结果收集到一个List.

有关另一种可读的方法,请参见下文。

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

.forEach 部分将遍历映射的 entrySet() 并将每个条目的键和值分别提取到 (键、值) 上。

仅使用设置和键查找的略有不同的变体:

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

这将使用流来解决问题:

expirationMap.entrySet().stream().filter(e -> e.getValue() > 3)
.forEach(e -> {
System.out.println("key " + e.getKey() + "value" + e.getValue());
});

除了其他人所做的之外,另一种方法是使用其默认方法test(T t)可用于计算大于 3 的值Interface Predicate<T>

Predicate<Long> filterGreater3 = f-> f>3;
expirationMap.entrySet()
.stream()
.filter(x->filterGreater3.test(x.getValue()))
.forEach(System.out::println);

最新更新