Is it possible to convert HashMap in java to List using MapStruct?

▼魔方 西西 提交于 2021-01-28 08:14:09

问题


We are trying to find a way to convert HashMap to List using mapstruct but there is no such help on the internet. Does anyone know a way to do it using mapstruct?

We have tried defining abstract class and use Abstract mapping but nothing works

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

Can’t generate mapping method from non-iterable type to iterable type.


回答1:


There is no out of the box support for converting Map into List. However, you can add a custom method.

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


来源:https://stackoverflow.com/questions/56805919/is-it-possible-to-convert-hashmap-in-java-to-list-using-mapstruct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!