Search code examples
javajava-streamcollectors

Using Collectors.toMap how to convert the map values


I have a Map<String, List<StartingMaterial>> I want to convert the Object in the List to another Object. ie. Map<String, List<StartingMaterialResponse>>

Can I do this using java stream Collectors.toMap()?

I tried something like the below code.

Map<String, List<StartingMaterial>>  startingMaterialMap = xxxx;

startingMaterialMap.entrySet().stream().collect(Collectors.toMap( Map.Entry::getKey, Function.identity(), (k, v) -> convertStartingMaterialToDto(v.getValue())));

And my conversion code to change the Object is like below,

private StartingMaterialResponse convertStartingMaterialToDto(StartingMaterial sm) {

    final StartingMaterialMatrix smm = sm.getStartingMaterialMatrix();
    final StartingMaterial blending1Matrix = smm.getBlending1Matrix();
    final StartingMaterial blending2Matrix = smm.getBlending2Matrix();

    return new StartingMaterialResponse(
            sm.getId(),
            sm.getComponent().getCasNumber(),
            sm.getDescription(),
            sm.getPriority(),
            String.join(" : ",
                    Arrays.asList(smm.getCarryInMatrix().getComponent().getMolecularFormula(),
                            blending1Matrix != null ? blending1Matrix.getComponent().getMolecularFormula() : "",
                            blending2Matrix != null ? blending2Matrix.getComponent().getMolecularFormula() : ""
                    ).stream().distinct().filter(m -> !m.equals("")).collect(Collectors.toList())),
            smm.getFamily(),
            smm.getSplitGroup());
}

Solution

  • You can use the toMap collector since your source is a map. However you have to iterate over all the values and convert each of them into the DTO format inside the valueMapper.

    Map<String, List<StartingMaterialResponse>> result = startingMaterialMap.entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream()
            .map(s -> convertStartingMaterialToDto(s)).collect(Collectors.toList())));