循环使用三个数组列表来比较值的有效方法

时间:2016-10-12 18:41:33

标签: for-loop spring-boot java-8 modelmapper

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

这是我正在做的... < / p>

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和Mapping

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

我想知道是否有更好的方法可以做到这一点,而且我使用ModelMapperSOrder映射到Order POJO,其他POJO希望知道是否有其他有效的模型映射器可用。
谢谢。

1 个答案:

答案 0 :(得分:0)

您可以productListorderList创建地图,其中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
  }
}