我有一个
Profile
对象 List<Profile> list
的列表。
我需要将其转换为
LinkedHashMap<String, String>
。
其中对象
Profile
的组成为:
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
方法引用表达式中的参数类型不兼容
确保您没有使用行类型列表作为流源。 IE。检查泛型类型参数是否丢失:
List list
(必须是List<Profile> list
),否则列表中所有类型为Object
的元素以及来自Profile
类的方法将无法访问。
默认情况下,
toMap
为您提供Map
的通用实现(目前是HashMap
但将来可能会改变)。
为了将流元素收集到
Map
接口的特定实现中,您需要使用需要四个参数的 Collectors.toMap()
风格:
keyMapper
- 生成键的映射函数,valueMapper
- 生成值的映射函数,mergeFunction
- 用于解决与同一键关联的值之间的冲突的函数,mapFactory
- 供应商提供一个新的空地图,结果将插入其中。在下面的代码中,
mergeFunction
没有做任何有用的事情,它只是必须存在才能利用允许指定toMap()
的mapFactory
版本。
Map<String, String> map = list.stream()
.collect(Collectors.toMap(
Profile::getFirstName,
Profile::getLastName,
(left, right) -> left,
LinkedHashMap::new
));
注意如果可能存在多个值与同一键关联的情况,您需要提供
mergeFunction
的正确实现(查看特定值或聚合值等) ,或使用 groupingBy()
作为收集器,这将允许保留与特定键关联的所有值。