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

fatherazrael :

How to convert from the list to map in Java 8 were in form of empID from within class and value as an object itself.

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

I want the second parameter in toMap as object itself. Could anyone suggest how to achieve the same?

I tried doing Collectors.toMap(CompanyEntity::getEmployeeId, this) but not able to get away from compile errors.

Andronicus :

You can use Function.identity() from java.util.function:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324032&siteId=1