mattsmith5
mattsmith5

Reputation: 1123

Java: Adding Child List to Parent Main List Iterating

We have a Product List, and ProductSubLine Items. We are taking productSubLineItems and adding them to the appropriate Product List. Is this an optimal way to do it, or any faster/algorithm way?

Classes:

public class Product {
    private long productId;
    private String productName;
    private BigDecimal costAmount;
    private List<ProductSub> productSublist;
}

public class ProductSub {
    private long productId;
    private long productSubId;
    private String lineItemName;
    private BigDecimal subCost;
}

Method:

List<Product> productList = ..(got from service)
List<ProductSub> productSubList = ..(got from service)

for (Product productItem : productList){
        List<ProductSub> productSubItems = productSubList.stream()
           .filter(x -> x.getProductId() == productItem.getProductId())
           .collect(Collectors.toList());
        productItem.setProductSubList(productSubItems);
    }

Upvotes: 0

Views: 31

Answers (1)

Ben Borchard
Ben Borchard

Reputation: 641

Your solution has you looping through the product sublist for each product. If you collect your list of ProductSubs in a map keyed by the id, then you only have to loop through the sublist once and then once through the product list:

Getting an object from a map is constant time complexity so this will be an O(n + m) whereas your solution with filtering and collecting to a list will be O(n * m), where n is the number of products and m is the number of product subs

As an example:

    Map<Long, List<ProductSub>> map = new HashMap<>();

    for (ProductSub productSub : productSubList) {
      map.computeIfAbsent(productSub.getProductId(), (k) -> new ArrayList<>()).add(productSub);
    }
    for (Product product : productList) {
      product.setProductSubList(map.get(product.getProductId()));
    }

Upvotes: 1

Related Questions