使用流,如何在HashMap中映射值? [英] Using streams, how can I map the values in a HashMap?

查看:185
本文介绍了使用流,如何在HashMap中映射值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定 Map< String,Person> 其中Person有一个 String getName()(etc)方法它,如何将 Map< String,Person> 转换为 Map< String,String> 其中字符串是从调用获取的人物:: getName()

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

Pre-Java 8我将使用

Pre-Java 8 I'd use

Map<String, String> byNameMap = new HashMap<>();

for (Map.Entry<String, Person> person : people.entrySet()) {
    byNameMap.put(person.getKey(), person.getValue().getName());
}

但我想用流和lambdas来做。

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

我无法看到如何以功能样式执行此操作:Map / HashMap未实现 Stream

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

people.entrySet()返回 Set< Entry< String,Person>> 我可以流过,但是如何将新的条目< String,String> 添加到目标地图?

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

推荐答案

使用Java 8,您可以:

With Java 8 you can do:

Map<String, String> byNameMap = new HashMap<>();
people.forEach((k, v) -> byNameMap.put(k, v.getName());

虽然你最好使用Guava的 Maps.transformValues ,它包装了原始的 Map 并在执行 get 时执行转换,这意味着您只需在实际使用该值时支付转换费用。

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.

使用Guava看起来像这样:

Using Guava would look like this:

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

编辑:

关注@ Eelco的评论(为了完整性),使用 Collectors.toMap 是这样的:

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

Map<String, String> byNameMap = people.entrySet()
  .stream()
  .collect(Collectors.toMap(Map.Entry::getKey, (entry) -> entry.getValue().getName());

这篇关于使用流,如何在HashMap中映射值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆