2016-03-28 31 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

相關問題