hashmap用stream流操作,使用流,如何在HashMap中映射值?

Given a Map where Person has a String getName() (etc) method on it, how can I turn the Map into a Map where the String is obtained from calling Person::getName()?

Pre-Java 8 I'd use

Map byNameMap = new HashMap<>();

for (Map.Entry person : people.entrySet()) {

byNameMap.put(person.getKey(), person.getValue().getName());

}

but I'd like to do it using streams and lambdas.

I can't see how to do this in a functional style: Map/HashMap don't implement Stream.

people.entrySet() returns a Set> which I can stream over, but how can I add a new Entry to the destination map?

解决方案

With Java 8 you can do:

Map byNameMap = new HashMap<>();

people.forEach((k, v) -> byNameMap.put(k, v.getName());

Though you'd be better off using Guava's Maps.transformValues, which wraps the original Map and does the conversion when you do the get, meaning you only pay the conversion cost when you actually consume the value.

Using Guava would look like this:

Map byNameMap = Maps.transformValues(people, Person::getName);

EDIT:

Following @Eelco's comment (and for completeness), the conversion to a map is better down with Collectors.toMap like this:

Map byNameMap = people.entrySet()

.stream()

.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> entry.getValue().getName());

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值