Java 8从Map中的匹配值中提取第一个键 [英] Java 8 extract first key from matching value in a Map
问题描述
假设我有一个给定名称,姓氏对的映射,并且我想在该映射中找到姓氏与某个值匹配的第一个条目的给定名称. 我们将如何以Java 8的方式做到这一点.
Suppose I have a map of given name, surname pairs and I want to find the given name of the first entry in that map that has the surname matching a certain value. How would we do this in a java 8 fashion.
在下面的测试案例中,我提出了两种实现方法.
In my test case example below I put two ways that would do it.
但是第一个(寻找姓氏为"Donkey"的第一个人的给定名称)将抛出java.util.NoSuchElementException:不存在任何值,因此不安全.
However the first one (looking for the given name of the first person with a surname of "Donkey") will throw java.util.NoSuchElementException: No value present so it is not safe.
第二种方法可以工作,但是它不仅难以阅读,而且功能还不太完善.
The second one works but it is not only harder to read but it it is a bit not quite functional.
只是想知道这里是否有人会建议我使用stream()
或forEach()
或同时使用这两种方法来实现此目的的更简单明了的方法.
Just wondering if someone here would suggest me an easier clearer way of achieving this using either stream()
or forEach()
or both.
@Test
public void shouldBeAbleToReturnTheKeyOfTheFirstMatchingValue() throws Exception {
Map<String, String> names = new LinkedHashMap<>();
names.put("John", "Doe");
names.put("Fred", "Flintstone");
names.put("Jane", "Doe");
String keyOfTheFirst = names.entrySet().stream().filter(e -> e.getValue().equals("Doe")).findFirst().get().getKey();
assertEquals("John", keyOfTheFirst);
try {
names.entrySet().stream().filter(e -> e.getValue().equals("Donkey")).findFirst().get();
} catch (NoSuchElementException e){
// Expected
}
Optional<Map.Entry<String, String>> optionalEntry = names.entrySet().stream().filter(e -> e.getValue().equals("Donkey")).findFirst();
keyOfTheFirst = optionalEntry.isPresent() ? optionalEntry.get().getKey() : null;
assertNull(keyOfTheFirst);
}
谢谢.
推荐答案
To return a default value if there is no match, use Optional#orElse
names.entrySet().stream()
.filter(e -> e.getValue().equals("Donkey"))
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
这篇关于Java 8从Map中的匹配值中提取第一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!