Java 8:如何从列表中创建映射,其中键是从相同的 class (empID) 和值作为对象 (Employee) 本身获取的?

Java 8: How to create map from list where Key is fetched from same class (empID) and value as object(Employee) itself?

如何从 Java 中的列表转换为映射 8 是在 class 中以 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) 但无法摆脱编译错误。

您可以使用 Function.identity() 来自 java.util.function:

Map<String, CompanyEntity> result1 = result.stream()
    .collect(Collectors.toMap(CompanyEntity::getEmployeeId, Function.identity()));