使用 Collectors.toMap 如何转换地图值

Using Collectors.toMap how to convert the map values

我有一个Map<String, List<StartingMaterial>> 我想将列表中的对象转换为另一个对象。 IE。 Map<String, List<StartingMaterialResponse>>

我可以使用 java 流 Collectors.toMap() 来做到这一点吗?

我试过类似下面的代码。

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

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

我更改对象的转换代码如下所示,

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());
}

您可以使用 toMap 收集器,因为您的源是地图。但是,您必须遍历所有值并将它们中的每一个转换为 valueMapper 中的 DTO 格式。

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())));

我想你的意思是:

startingMaterialMap.entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey,
                e -> e.getValue().stream()
                        .map(this::convertStartingMaterialToDto)
                        .collect(Collectors.toList()))
        );

这是我解决这个问题的方法:

    Map<String, List<Integer>> deposits = new HashMap<>();

    deposits.put("first", Arrays.asList(1, 2, 3));

    deposits.forEach((depositName, products) -> {
        products.stream()
                .map(myIntegerProduct -> myIntegerProduct.toString())
                .collect(Collectors.toList());
    });

以上示例将 List<Integer> 转换为字符串列表。 在您的示例中,myIntegerProduct.toString()convertStartingMaterialToDto 方法。

forEach 方法遍历映射中的每个 Key-Value 对,并为键设置一些名称和值参数更具体,并为阅读它的每个人保留可理解的代码。在我的示例中:forEach( (depositName, products)) -> depositName 是键(在我的例子中是一个字符串)而 products 是键的值(在我的例子中是一个整数列表)。

最后你也遍历了列表并且map每个项目都变成了一个新类型

products.stream() .map(myIntegerProduct -> myIntegerProduct.toString())