Search code examples
javadictionaryarraylistjava-8collectors

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


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.


Solution

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

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