我有Deal
个对象,它有subDeals
(Deal
列表),我需要更新subDeals
。 DealDTO
对象包含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
。
答案 0 :(得分:2)
由于您提到列表很大,因此您可以采取一些措施来改善性能。
codes
以用于子项目。提供一个getter List<Deal> getSubDeals
,在需要时创建列表并返回。