Elad Benda
Elad Benda

Reputation: 36656

Why cannot I access the type field when using Collectors.toMap?

why cannot I access the id property of Device ?

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

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

where

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

see here:

enter image description here

Upvotes: 1

Views: 447

Answers (1)

Eran
Eran

Reputation: 393781

You got a misleading error message. The actual error is using a ConcurrentMap<Integer, Device> type when the type returned by the collector is Map<Integer, Device>.

If you want the returned Map to be a ConcurrentMap, you can use the toMap variant that accepts a supplier (which determines the type of the Map to be returned).

Something like this should work :

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

or as Alexis commented, just use Collector.toConcurrentMap.

Upvotes: 2

Related Questions