我正在使用 Java 8,我尝试使用“Collectors.groupingBy”,但没有获得所需的格式public class ConsigneeLoadDetails { private Integer tripID; private String consignor; private String consignee; private String city; private Double distanceToNext; private Double load; private Integer cap; private Integer vehicleCapacity; private Double cLoad; private Integer truckUtilisation; private Double latitude; private Double longitude; // getter , setter of all parameters }List
listConsigneeLoadDetails = new ArrayList();// loop to add ConsigneeLoadDetailslistConsigneeLoadDetails.add(consigneeLoadDetails);我在 API 响应中低于 Json我想要以下格式的回复
查看完整描述
TA贡献1705条经验 获得超10个赞
你为什么不重新安排你的 POJO 类,像这样
public class ConsigneeLoadDetails {
private Integer tripID;
private String consignor;
private Integer vehicleCapacity;
private Double cLoad;
private Integer truckUtilisation;
private List<consigneeDetails> consigneeDetails
private Double latitude;
private Double longitude;
// getter , setter of all parameters
}
public class ConsigneeDetails {
private String consignee;
private String city;
private Double distanceToNext;
private Double load;
private Integer cap;
// getter , setter of all parameters
}
查看完整回答
TA贡献1733条经验 获得超6个赞
Map<Integer, List<ConsigneeLoadDetails>> collect =
// group the object by id
listConsigneeLoadDetails.stream().collect(Collectors.groupingBy(consigneeLoadDetails -> consigneeLoadDetails.tripID));
List<ConsigneeLoadDetailsDto> dtoList = new ArrayList<>();
collect.forEach((integer, consigneeLoadDetails) -> {
List<ConsigneeLoadDetails> list = consigneeLoadDetails;
if (Optional.ofNullable(list).isPresent() && !list.isEmpty()) {
ConsigneeLoadDetailsDto dtos = new ConsigneeLoadDetailsDto();
dtos.setTripID(integer);
dtos.setConsignor(list.stream().findFirst().get().getConsignor());
dtos.setVehicleCapacity(list.stream().findFirst().get().getVehicleCapacity());
dtos.setCLoad(list.stream().findFirst().get().getCLoad());
dtos.setTruckUtilisation(list.stream().findFirst().get().getTruckUtilisation());
List<ConsigneeDetails> consigneeDetails = new ArrayList<>();
list.forEach(next -> {
ConsigneeDetails con = new ConsigneeDetails();
con.setCap(next.getCap());
con.setCity(next.getCity());
con.setConsignee(next.getConsignee());
con.setDistanceToNext(next.getDistanceToNext());
con.setLoad(next.getLoad());
consigneeDetails.add(con);
});
dtos.setConsigneeDetails(consigneeDetails);
dtoList.add(dtos);
}
});
// Your result will be store in
// dtoList
}
}
@Getter
@Setter
@ToString
class ConsigneeLoadDetailsDto {
private Integer tripID;
private String consignor;
private Integer vehicleCapacity;
private Double cLoad;
private Integer truckUtilisation;
private List<ConsigneeDetails> consigneeDetails;
}
@Getter
@Setter
@ToString
class ConsigneeDetails {
private String consignee;
private String city;
private Double distanceToNext;
private Double load;
private Integer cap;
}
查看完整回答