【问题标题】:Why cannot I access the type field when using Collectors.toMap?为什么在使用 Collectors.toMap 时无法访问类型字段?
【发布时间】:2016-03-28 09:48:38
【问题描述】:

为什么我无法访问Deviceid 属性?

final List<Device> devicesList = jsonFileHandlerDevice.getList();

ConcurrentMap<Integer, Device> map =
        devicesList.stream()
                   .collect(Collectors.toMap(item -> item.id, item -> item));

在哪里

public class Device {

    public MobileOs mobileOs;
    public Integer id;


    public Device() {
    }

    public Device(MobileOs mobileOs, double osVersion, int allocatedPort, Integer id, String uuid) {
        this.mobileOs = mobileOs;
        this.id = id;
    }
}

看这里:

【问题讨论】:

  • 我想您可能收到了误导性的错误信息。我相信当收集器返回的类型是Map&lt;Integer, Device&gt; 时,实际的错误是使用ConcurrentMap&lt;Integer, Device&gt; 类型。如果您希望返回的 MapConcurrentMap,则必须使用接受供应商的 toMap 变体(确定要返回的 Map 的类型)。
  • 查看我添加的截图
  • 错误信息是什么?
  • 我就是无法访问成员“id”
  • @EladBenda 这可能是您的 IDE 的错误。尝试将map的类型更改为Map,看看错误是否消失。

标签: java list dictionary lambda java-stream


【解决方案1】:

您收到了误导性的错误消息。当收集器返回的类型为Map&lt;Integer, Device&gt; 时,实际错误是使用ConcurrentMap&lt;Integer, Device&gt; 类型。

如果您希望返回的MapConcurrentMap,您可以使用接受供应商的toMap 变体(它确定要返回的Map 的类型)。

这样的事情应该可以工作:

ConcurrentMap<Integer, Device> map =
        devicesList.stream()
                .collect(Collectors.toMap(item -> item.id,
                                          item -> item,
                                          (item1,item2)->item2,
                                          ConcurrentHashMap::new));

或者正如亚历克西斯所说,只需使用Collector.toConcurrentMap

【讨论】:

  • "你必须使用 toMap 变体" ...或者干脆使用Collectors.toConcurrentMap
  • @AlexisC.我没有意识到这一点。我没有想到 API 可能包含这样的收集器。谢谢:)
猜你喜欢
  • 2021-10-01
  • 2015-05-16
  • 2020-08-02
  • 2014-09-21
  • 1970-01-01
  • 2018-09-23
  • 1970-01-01
  • 2021-08-02
  • 2013-08-16
相关资源
最近更新 更多