2016-03-28 109 views
1

为什么我无法访问Deviceid属性?为什么在使用Collectors.toMap时无法访问类型字段?

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; 
    } 
} 

在这里看到:

enter image description here

+0

我想也许你得到了一个误导性的错误信息。当收集器返回的类型是Map '时,我相信实际的错误是使用'ConcurrentMap '类型。如果你希望返回的'Map'是一个'ConcurrentMap',你必须使用'toMap'变体来接受一个供应商(它决定了要返回的映射的类型)。 – Eran

+0

看我添加的截图 –

+0

什么是错误信息? –

回答

2

你有误导性的错误消息。当收集器返回的类型为Map<Integer, Device>时,实际的错误是使用ConcurrentMap<Integer, Device>类型。

如果你想返回Map是一个ConcurrentMap,您可以使用toMap变种,接受供应商(决定Map的类型要返回)。

像这样的东西应该工作:

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

或亚历克西斯评论,只是用Collector.toConcurrentMap

+0

_“您必须使用toMap变体”_ ...或仅使用“Collectors.toConcurrentMap”。 –

+0

@ AlexisC.I没有意识到这一点。我没有想到API可能包含这样一个收集器。谢谢 :) – Eran

相关问题