使用Sub对象

时间:2015-08-13 10:06:36

标签: java list arraylist java-8

我有Deal个对象,它有subDealsDeal列表),我需要更新subDealsDealDTO对象包含subCodes列表,因此我需要找到每个Deal的{​​{1}}对象,并将subCodes更新为subDeals

以下是Deal类:

Deal

这是public class Deal { String code; BigDecimal price; List<Deal> subDeals; public Deal(String code, BigDecimal price) { super(); this.code = code; this.price = price; this.subDeals = new ArrayList<>(); } // geteer setter public void addSubDeal(Deal subDeal) { subDeals.add(subDeal); } }

DealDTO

以下是我尝试的方法,但它不起作用:

public class DealDTO {
    private String masterCode;
    private List<String> subCodes;
    public DealDTO(String masterCode, List<String> subCodes) {
        super();
        this.masterCode = masterCode;
        this.subCodes = subCodes;
    }
    // geteer setter
}

列表很大,所以我想确保我按照正确的方法更新List<Deal> masterDeals = Arrays.asList( new Deal("ABC",new BigDecimal(5)), new Deal("DEF",new BigDecimal(10)), new Deal("GHI",new BigDecimal(15)) ); List<DealDTO> dealDTOs = Arrays.asList( new DealDTO("ABC", Arrays.asList("JKL")), new DealDTO("DEF", Arrays.asList("JKL", "ABC")), new DealDTO("GHI", Arrays.asList("MNO")) ); DealDTO dealDTO = null; for(Deal masterDeal : masterDeals) { // get DealDTO which matches with masterDeal's code dealDTO = dealDTOs.stream() .filter(dto -> dto.getMasterCode().equals(masterDeal.getCode())) .findFirst() .get(); // if subCodes are present then traverse through it and get the Deal object from masterDeals list and update the masterDeal if(dealDTO.getSubCodes() != null && !dealDTO.getSubCodes().isEmpty()) { dealDTO.getSubCodes().stream().forEach( code -> { for(Deal deal : masterDeals) { if(deal.getCode().equals(code)) { masterDeal.addSubDeal(deal); } } }); } // subDeals has been added so persist masterDeal here } masterDeals.forEach(System.out::println); // throws java.lang.StackOverflowError

1 个答案:

答案 0 :(得分:2)

由于您提到列表很大,因此您可以采取一些措施来改善性能。

  1. 使用地图来保留交易而不是列表。给定代码,您应该能够快速检索交易。
  2. 如果可能的话,让交易仅保存codes以用于子项目。提供一个getter List<Deal> getSubDeals,在需要时创建列表并返回。