javadictionarylambdajava-streamcollectors

Using a stream instead of a for loop to create a Map


I am working on a Java project where I have to iterate a list and put values in a new map based on computations in that list.

Here's whats working using a basic for loop:

   Map<Long, PickingDetails> pickingDetailsDTOMap = new HashMap<>();
   for(int i=0;i<pickingJobModels.size();i++)
    {
pickingDetailsDTOMap.put(pickingJobModels.get(i).getPickListDTO().getReferenceId(),getPickingDetails(pickingJobModels.get(i)));
     }

But I want to do it with streams so I did this:

pickingJobModels.stream().map(pickingJobModel -> pickingDetailsDTOMap.put(pickingJobModel.getPickListDTO().getReferenceId(),getPickingDetails(pickingJobModel)));

but when I return that pickingDetailsDTOMap I get empty map.

Any suggestions how to use a stream in this case?


Solution

  • That's not the correct way. map is an intermediate operation (i.e. it is evaluated lazily) and you have no terminal operation, so it's never evaluated. You should collect the data into a Map:

    Map<Long, PickingDetails> pickingDetailsDTOMap = 
        pickingJobModels.stream()
                        .collect(Collectors.toMap(pm -> pm.getPickListDTO().getReferenceId(),
                                                  pm -> getPickingDetails(pm)));