基于Java streams的ID将数据合并在一起
目前,我在java应用程序中从API中提取了一组数据。返回的数据如下所示:
{
"id": 1,
"receiptId": "123456",
"selections": [
{
"name": "Apple",
"price": "£1"
}
]
},
{
"id": 2,
"receiptId": "678910",
"selections": [
{
"name": "Pear",
"price": "£0.5"
}
]
},
{
"id": 3,
"receiptId": "123456",
"selections": [
{
"name": "Banana",
"price:": "£2.00"
}
]
}
如您所见,其中两个receiptId
是相同的,我想将任何重复的receiptId's
数据合并成一个块。即:
{
"id": 1,
"receiptId": "123456",
"selections": [
{
"name": "Apple",
"price": "£1"
},
{
"name": "Banana",
"price": "£2.00"
}
]
},
{
"id": 2,
"receiptId": "678910",
"selections": [
{
"name": "Pear",
"price": "£0.5"
}
]
},
目前,我正在通过以下操作将数据流式传输到地图中:
List<String> data = data.getData()
.stream()
.map(this::dataToReadable)
.collect(Collectors.toList());
dataToReadable
执行以下操作:
private String dataToReadable(List data) {
return new DataBuilder().fromData(data)
.buildData();
}
fromData
执行以下操作:
public DataBuilder fromData(List data) {
this.withId(data.getId())
this.withSelections(data.getSelections())
this.withReceiptId(data.getReceiptId())
return this;
}
# 1 楼答案
看看这是否有效