为什么在使用collectors.tomap时不能访问type字段?

gcuhipw9  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(343)

为什么我不能访问 id 财产 Device ?

  1. final List<Device> devicesList = jsonFileHandlerDevice.getList();
  2. ConcurrentMap<Integer, Device> map =
  3. devicesList.stream()
  4. .collect(Collectors.toMap(item -> item.id, item -> item));

哪里

  1. public class Device {
  2. public MobileOs mobileOs;
  3. public Integer id;
  4. public Device() {
  5. }
  6. public Device(MobileOs mobileOs, double osVersion, int allocatedPort, Integer id, String uuid) {
  7. this.mobileOs = mobileOs;
  8. this.id = id;
  9. }
  10. }

请看这里:

7vhp5slm

7vhp5slm1#

你收到了一条误导性的错误信息。实际错误是使用 ConcurrentMap<Integer, Device> 当收集器返回的类型为 Map<Integer, Device> .
如果你想退货 Map 成为一个 ConcurrentMap ,您可以使用 toMap 接受供应商的变量(确定供应商的类型) Map 待退回)。
这样的方法应该有用:

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

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

相关问题