有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

基于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) 个答案

  1. # 1 楼答案

    看看这是否有效

     data.getData()
            .stream()
            .collect(Collectors.groupingBy(Data::getRecieptId))
            .entrySet()
            .stream()
            .map(item -> dataToReadable(item.getValue()))
            .collect(Collectors.toList());