使用 Java 8 将对象列表收集到 LinkedHashMap 中

问题描述 投票:0回答:1

我有一个

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
java hashmap java-stream linkedhashmap
1个回答
2
投票

方法引用表达式中的参数类型不兼容

确保您没有使用行类型列表作为流源。 IE。检查泛型类型参数是否丢失:

List list
(必须是
List<Profile> list
),否则列表中所有类型为
Object
的元素以及来自
Profile
类的方法将无法访问。


收集到 LinkedHashMap

默认情况下,

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()
作为收集器,这将允许保留与特定键关联的所有值。

© www.soinside.com 2019 - 2024. All rights reserved.