【发布时间】:2021-08-19 16:03:05
【问题描述】:
我有两个相同类型的列表: 框 1 和框 2:
"boxes1": [{
"boxId": "ABC",
"ele": [{
"eleId": "8040",
"chars": [{
"no": "123",
"qty": 2
}
]
}
]
}, {
"boxId": "XYZ",
"ele": [{
"eleId": "1212",
"chars": [{
"no": "456",
"qty": 3
}
]
}
]
}
]
和
"boxes2": [{
"boxId": "ABC",
"ele": [{
"eleId": "8040",
"chars": [{
"no": "123",
"qty": 6
}
]
}, {
"eleId": "4560",
"chars": [{
"no": "012",
"qty": 3
}
]
}
]
}, {
"boxId": "PQR",
"ele": [{
"eleId": "1111",
"chars": [{
"no": "456",
"qty": 8
}
]
}
]
}
]
我想检查 boxes1 中的任何 boxId 是否与 boxes2 中的 boxId 匹配,然后我想将box1的一个公共元素eleId的chars添加到box2中,这样组合后的结果是这样的:
"box2": [{
"boxId": "ABC",
"ele": [{
"eleId": "8040",
"chars": [{
"no": "123",
"qty": 6
},
{
"no": "123",
"qty": 2
}
]
},.....................
如果 Boxes1 中有任何 boxId 不存在于 Boxes2 我想将该框添加到 盒子2。所以最后它应该看起来像:
"box2": [{
"boxId": "ABC",
"ele": [{
"eleId": "8040",
"chars": [{
"no": "123",
"qty": 6
}, {
"no": "123",
"qty": 2
}
]
}, {
"eleId": "4560",
"chars": [{
"no": "012",
"qty": 3
}
]
}
]
}, {
"boxId": "PQR",
"ele": [{
"eleId": "1111",
"chars": [{
"no": "456",
"qty": 8
}
]
}
]
}, {
"boxId": "XYZ",
"ele": [{
"eleId": "1212",
"chars": [{
"no": "456",
"qty": 3
}
]
}
]
}
]
我是 Stream 的新手,所以尝试使用旧方法,但它有问题:
boxes2.forEach(box2 -> {
boxes1.forEach(box1 -> {
if (box1.getBoxId().equals(box2.getBoxId())) {
box2.getEle().forEach(ele1 -> {
box1.getEle().forEach(ele2 -> {
if (ele1.getEleId().equals(ele2.getEleId())) {
ele1.chars().addAll(ele2.chars());
}
});
});
} else {
boxes2.add(box1);
}
});
});
【问题讨论】:
-
到目前为止你有什么尝试?
-
添加到问题中,谢谢。
-
该代码不可读且非常嵌套。老实说,我不确定你想用它来实现什么。另外,您的 JSON 列表在代码中是如何表示的?
-
是的,代码有问题,但你明白这里的问题吗?
-
这是我喜欢 javascript 的时候之一。这东西在javascript中真的很简单
标签: java java-8 java-stream backend