【问题标题】:Is it possible to convert HashMap in java to List using MapStruct?是否可以使用 MapStruct 将 java 中的 HashMap 转换为 List?
【发布时间】:2019-07-03 15:14:50
【问题描述】:

我们正在尝试找到一种使用 mapstruct 将 HashMap 转换为 List 的方法,但互联网上没有这样的帮助。有谁知道使用 mapstruct 的方法吗?

我们尝试定义抽象类并使用抽象映射,但没有任何效果

@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN,
implementationPackage = "com.mapstruct.mapper.impl")
public abstract class OrderLineMapper {
  public com.internal.epfo.v1.OrderLine toOrderLineList(Map.Entry<Integer, OrderLine> orderLineEntry) {
    com.internal.epfo.v1.OrderLine orderLine = new com.internal.epfo.v1.OrderLine();
    orderLine.setCategoryTypeCode(orderLineEntry.getValue().getCategoryTypeCode());
    orderLine.getProducts().addAll(getProductInfoList(orderLineEntry.getValue().getProducts()));
    return orderLine;
  }

  List<com.internal.epfo.v1.ProductInfo> getProductInfoList(EnrichProductInfoMap<String, ProductInfo> products) {
    List<com.internal.epfo.v1.ProductInfo> productInfo = products.values().stream().collect(Collectors.toCollection( ArrayList<com.internal.epfo.v1.ProductInfo>::new ));
    return productInfo;
  }

  @MapMapping
  public abstract List<com.internal.epfo.v1.OrderLine> toOrderLineList(
      Map<Integer, OrderLine> orderLine);
}

无法生成从不可迭代类型到可迭代类型的映射方法。

【问题讨论】:

  • 不相关:考虑导入您的类型,而不是到处使用完全限定的类型来产生如此令人难以置信的线路噪音。仅此一项就使您的代码比必要的难于阅读 10 倍。
  • 这可能是一个重复的问题。请看:stackoverflow.com/questions/47451671/…

标签: java mapstruct


【解决方案1】:

没有现成的支持将Map 转换为List。但是,您可以添加自定义方法。

public abstract class OrderLineMapper {
  public OrderLineV1 toOrderLine(Map.Entry<Integer, OrderLine> orderLineEntry) {
    OrderLineV1 orderLine = new OrderLineV1();
    orderLine.setCategoryTypeCode(orderLineEntry.getValue().getCategoryTypeCode());
    orderLine.getProducts().addAll(getProductInfoList(orderLineEntry.getValue().getProducts()));
    return orderLine;
  }

  List<ProductInfoV1> getProductInfoList(EnrichProductInfoMap<String, ProductInfo> products) {
    List<ProductInfoV1> productInfo = products.values().stream().collect(Collectors.toCollection( ArrayList<ProductInfoV1>::new ));
    return productInfo;
  }

  public List<OrderLineV1> toOrderLineList(Map<Integer, OrderLine> orderLine) {
    return orderLine == null ? null : toOrderLineList(orderLine.entrySet());
  }

  public abstract List<OrderLineV1> toOrderLineList(Collection<Map.Entry<Integer, OrderLine> orderLineCollection);
}

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 2021-12-05
    • 1970-01-01
    • 2015-10-14
    相关资源
    最近更新 更多