获取组对象列表

时间:2018-11-06 12:34:13

标签: java collections

我有一个叫做truck的Java类,另一个叫truckparts的类。我想获得以下指定格式的输出集合。我尝试了不适用于我的收藏,并给了我未预期的结果。

public class Truck {
    private String name;
    private int qty;
    private BigDecimal price;
    private List<Integer> platIds = new ArrayList<>();
    // Constructor and getters and setters 

我还有另一堂课:

public class TruckParts {
    private Integer id;
    private String namepart;
    private int qtypart;
    private BigDecimal pricepart;
    private Truck truck = new Truck();
    // Constructor and getters and setters 

我收到了如下所示的对象列表形式的输入:

[
  {
    "id": 1,
    "namepart":"val",
    "qtypart":"fg",
    "pricepart":120,
    "name":"valasdhjk",
    "qty" :"sdfg",
    "price":123,
    "partid":1
   },
   {
    "id": 1,
    "namepart":"val",
    "qtypart":"fg",
    "pricepart":120,
    "name":"valasdhjk",
    "qty" :"sdfg",
    "price":123,
    "partid": 1
   },
   {
    "id": 2,
    "namepart":"val",
    "qtypart":"fg",
    "pricepart":120,
    "name":"valasdhjk",
    "qty" :"sdfg",
    "price":123,
    "partid":1
   },
   {
    "id": 2,
    "namepart":"val",
    "qtypart":"fg",
    "pricepart":120,
    "name":"valasdhjk",
    "qty" :"sdfg",
    "price":123,
    "partid":2
   }
]

现在,我希望此输出转换为以下形式:

[
  {
    "id": 1,
    "namepart":"val",
    "qtypart":"fg",
    "pricepart":120,
    "truck":{
            "name":"valasdhjk",
            "qty" :"sdfg",
            "price":123,
            "partids":[1,2]
     }

   },

   {
    "id": 2,
    "namepart":"val",
    "qtypart":"fg",
    "pricepart":120,
    "truck:"{
          "name":"valasdhjk",
          "qty" :"sdfg",
          "price":123,
          "partids":[1,2]
     }
   }
]

我已经尝试过地图。

 Map<BigDecimal, List<TruckParts>> groupByid = 
        items.stream().collect(Collectors.groupingBy(TruckParts::getId));

但是这似乎不是我想要的。有人可以告诉我获得此结果的最佳方法吗?

1 个答案:

答案 0 :(得分:1)

您正在朝着正确的方向前进:

 Map<BigDecimal, List<TruckParts>> groupById = 
        items.stream().collect(Collectors.groupingBy(TruckParts::getId));

有了该Map<BigDecimal, List<TruckParts>>,您可以将每个条目映射到Truck对象中:

groupById.entrySet().stream().map(x -> {
    // assuming your constructor's parameters go in the order of name, qty, price, platIds
    return new Truck(x.getValue().get(0).getNamePart(), 
              x.getValue().get(0).getQtyPart(), 
              x.getValue().get(0).getPricePart(),
              x.getValue().stream().map(TruckPart::getPartId).collect(Collectors.toList()));
})