gpt4 book ai didi

java - 如何连接具有相同键属性的对象列表

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:43 25 4
gpt4 key购买 nike

如果对象的特定关键属性匹配,我正在尝试连接自定义对象

我正在获取以下格式的数据。

List is like this.

 Data[
{batchNo: "1212", location: "12bbn", qty: "123", rawMaterialId: "6743"},
{batchNo: "1213", location: "12nmn", qty: "300", rawMaterialId: "6743"},
{batchNo: "1241", location: "vbv2", qty: "123", rawMaterialId: "9179"},
{batchNo: "1251", location: "fdsfds", qty: "244", rawMaterialId: "9179"},
{batchNo: "1233", location: "cvcvbc", qty: "200", rawMaterialId: "9169"},
{batchNo: "1266", location: "bnbn", qty: "600", rawMaterialId: "9935"}
]

我正在尝试根据特定的关键属性(即( rawMaterialId )连接它们。

例如,如果 rawMaterialId=6743 of index[0] 与 index[1] 匹配,则两者都需要连接。

Expected List

    Data[
{batchNo: "1212 , 1213", location: "12bbn , 12nmn", qty: "123 , 300", rawMaterialId: "6743"},
{batchNo: "1241,1251", location: "vbv2 , fdsfds", qty: "123,244",rawMaterialId: "9179"},
{batchNo: "1233", location: "cvcvbc", qty: "200", rawMaterialId:"9169"},
{batchNo: "1266", location: "bnbn", qty: "600", rawMaterialId: "9935"}
]

我试过使用 For 循环但没有得到预期的输出

Code which I tried

       for(int i=0; i<data.length;i++)
{
for(int j=0; i<data.length;i++)
{
if(data[i].rawMaterialId == data[j].rawMaterialId )
{
data[i].location=data[i].location +","+ data[j].location;
data[i].batchNo=data[i].batchNo +"," + data[j].batchNo;
data[i].quantity=data[i].quantity +"," + data[j].quantity;
}
}
}

请帮我解决这个问题,欢迎任何建议和更正。提前致谢。

最佳答案

如果您有数组数据,您可以使用stream api 来转换它。最后一行将 Data 替换为您项目的真实类型。

data = Arrays.stream(data).       // Create stream from your array
collect(Collectors.toMap( // Transform it to Map
d -> d.rawMaterialId, // It is keys of creating map
d -> d, // This is values of creating map
(d1, d2) -> { // Function for merging values with same keys.
// There happens all neded concatenations.
d1.location = d1.location + "," + d2.location;
d1.batchNo = d1.batchNo + "," + d2.batchNo;
d1.quantity = d1.quantity + "," + d2.quantity;
return d1;
}).
values().toArray(new Data[0]); // Transform map to new array.
// Replace Data to real type of your items.

关于java - 如何连接具有相同键属性的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47986498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com