java map取第一个元素,Java 8从Map中的匹配值中提取第一个键

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.

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.

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 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> optionalEntry = names.entrySet().stream().filter(e -> e.getValue().equals("Donkey")).findFirst();

keyOfTheFirst = optionalEntry.isPresent() ? optionalEntry.get().getKey() : null;

assertNull(keyOfTheFirst);

}

Thank you in advance.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值