0

我有两个 arraylist 对象orderListproductList一个 String arraylist customerIdList
我有ProductInfoPOJO 与 orderList 和 productList 映射,其中 customerId 应该匹配。
如果我没有给定 ProdId 的订单或产品列表,我应该添加标准错误并映射到 ProductInfo 错误。

这就是我正在做的...

public class ProductInfo {
    private List<ProductDetails> products;
    private List<Error> errors;
    private String customerId;
}

public class ProductDetails {
    private String customerId;
    private Order order;
    private Product product;
    private List<Error> errors;
}

样本结果...

{
    "productInfo": {
        "customer_id": "123",
        "product_details": [
        {
            "customer_id": "123",
            "order_details": null,
            "product_details": {
                "customer_id": "123"
                "product_id" : "2343"
                "product_name": "XYZ",
                "product_type": "PQR"
                ...
            },
            "errors": [
                "error_code":"6001",
                "error_desc":"Failure in getting Order information from Order Service"
            ]
        },
        {
            "order_details": {
                "customer_id":"123"
                "order_id": "3543454",
                "order_date":"2016-10-12",
                "order_status":"ordered"
            },
            "product_details": null,
            "errors": [
                "error_code":"6001",
                "error_desc":"Failure in getting Product information from Product Service"
            ]
        }
        ],
        "system_errors":[]  
    }
}   

循环遍历 ArrayList 和映射

for(String customerId : customerIdList) {   
    for(Product product: productList) {
        for(SOrder ordr: orderList) {
            if(customerId.equals(product.getCustomerId()) && customerId.equals(Order.getCustomerId()) ) {
                ModelMapper mapper = new ModelMapper();
                Order order = mapper.map(ordr, Order.class));
                productDetails.setOrder(order);
                //mapping to ProductInfo
                productDetailsList.add(productDetails);
            }
        }
    }
}

我想知道是否有更好的方法可以做到这一点,而且我正在使用ModelMapper映射SOrderOrderPOJO,
其他 POJO 想知道是否有任何其他有效的模型映射器可用。
谢谢。

4

1 回答 1

0

productList您可以orderList使用customerId作为键创建地图

Map<String, Product> productMap = productList.stream().collect(Collectors.toMap(p -> p.getCustomerId(), p -> p));
Map<String, Product> orderMap = orderList.stream().collect(Collectors.toMap(o -> o.getCustomerId(), o -> o));

然后只需一个循环,您就可以检查该客户 ID 是否有产品和订单

for(String customerId : customerIdList) {
  if (productMap.containsKey(customerId) && orderMap.containsKey(customerId)) {
    //do your mapping stuff here
  }
}
于 2016-10-12T19:26:40.773 回答