将对象列表收集到使用Java 8的LinkedHashmap中
我有配置文件
对象 list< profile>列表
。
我需要将其转换为 linkedhashmap< string,string>
。
如果对象配置文件
包括:
public class Profile {
private String profileId;
private String firstName;
private String lastName;
}
我尝试了以下操作:
Map<String, String> map = list.stream()
.collect(Collectors.toMap(Profile::getFirstName,
Profile::getLastName));
但是它不起作用,我遇到了汇编错误:
Incompatible parameter types in method reference expression
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确保您不使用 Row Type 作为流源的列表。 IE检查是否缺少通用类型参数:
列表
(必须为list&lt; profile&gt; list
),否则列表的所有元素都为类型对象
和配置文件>类的方法将无法访问。
默认为linkedhashmap。
默认情况下,
tomap
为您提供了map
(目前是hashmap ,但它可能会在将来发生变化)。
为了将流元素收集到
MAP
接口的特定实现中,您需要使用collectors.tomap()
期望四个参数:keymapper
- 生产密钥,MergeFunction
- 函数,旨在解决与同一密钥相关的值之间的碰撞,mapfactory
- 供应商提供新的空图将插入结果。在下面的代码中,
MergeFunction
没有做任何有用的事情,它只需要存在才能使用tomap()
的版本,该版本允许指定mapFactory
。注释 如果可能在某些情况下,一个以上值与同一键关联,则需要提供适当的实现
MergeFunction
( 查看特定的值或汇总值等,或使用),或使用groupingby()
作为收集器,它将允许保留与特定密钥相关的所有值。Make sure that you're not using a list of row type as a stream source. I.e. check if the generic type parameter is missing:
List list
(it has to beList<Profile> list
), otherwise all elements of the list as being of typeObject
and methods from theProfile
class would not be accessible.Collecting into a LinkedHashMap
By default,
toMap
provides you with a general purpose implementation of theMap
(for now it'sHashMap
but it might change in the future).In order to collect stream elements into a particular implementation of the
Map
interface, you need to use a flavor ofCollectors.toMap()
that expects four arguments:keyMapper
- a mapping function to produce keys,valueMapper
- a mapping function to produce values,mergeFunction
- function that is meant to resolve collisions between value associated with the same key,mapFactory
- a supplier providing a new empty Map into which the results will be inserted.In the code below,
mergeFunction
isn't doing anything useful, it just has to be present in order to utilize the version oftoMap()
that allows to specify themapFactory
.Note if there could be cases when more than one value gets associated with the same key, you need either to provide a proper implementation of
mergeFunction
(to peek a particular value or aggregate values, etc.), or usegroupingBy()
as a collector, which will allow to preserve all values associated with a particular key.