简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM