java - 使用子对象列表更新主对象列表

标签 java list arraylist java-8

我有 Deal 对象,它有 subDeals (Deal 列表),我需要更新 subDeals >。 DealDTO 对象具有 subCodes 列表,因此我需要找到每个 subCodesDeal 对象并更新 >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

列表很大,因此我想确保遵循正确的方法来更新subDeals

最佳答案

既然您提到列表很大,您可以采取一些措施来提高性能。

  1. 使用 map 而不是列表来保存交易。给定代码,您应该能够快速检索交易。
  2. 如果可能的话,让交易也只节省codes用于子交易。提供 setter/getter List<Deal> getSubDeals在需要时创建列表并返回。

关于java - 使用子对象列表更新主对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31985220/

相关文章:

java - 如何从Json字符串中删除双引号 ""

java - 从 JTextFields 发送到数组

java - 如何根据文件中的数据类型将 CSV 文件读入 2 个 ArrayList?

java - 当你尝试反混淆奇怪的代码时如何处理名称冲突?

java - BlackJack Java String[] 不工作

Python递归执行try except while条件满足

string - 在 Python 3 中检查字符串是否包含重复字符的最快方法是什么?

java - 在 doInBackground 方法中使用比较器对 ArrayList 进行排序时出错

java - 我正在尝试使用 selenium webdriver、testng 和页面工厂实现自动化。但我面临空指针异常

python - 计算列表列表中的不同值 - Python