问题
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