Java 8:如何从列表创建映射,其中键从同一类(empID)获取,值作为对象(Employee)

如何在 Java 8 中从列表转换为映射的形式是empID从类内转换,并将值作为对象本身。

List<CompanyEntity> result = 
             ifEntityManager.createNamedQuery("findByEmployeeId", CompanyEntity.class)
             .getResultList();
Map<String, CompanyEntity> result1 = result.stream()
        .collect(Collectors.toMap(CompanyEntity::getEmployeeId, CompanyEntity::this)); ??

我想要第二个参数作为toMap对象本身。谁能建议如何实现同样的目标?

我尝试这样做Collectors.toMap(CompanyEntity::getEmployeeId, this),但无法摆脱编译错误。


温温酱
浏览 58回答 1
1回答

摇曳的蔷薇

您可以Function.identity()使用java.util.function:Map<String,&nbsp;CompanyEntity>&nbsp;result1&nbsp;=&nbsp;result.stream() &nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toMap(CompanyEntity::getEmployeeId,&nbsp;Function.identity()));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java