我有一个List<CropDetailDto>
由Postgresql中的本机查询的Hibernate Projection返回。
我想以分层/树格式表示它,以将其作为响应发送。
我在Collectors.groupingBy
上使用了多个嵌套的List<CropDetailDto>
public Map<String, Map<String, Map<String, List<CropDetailDto>>>> findCropDetails() {
List<CropDetailDto> cropdetails = cropRepository.getCropDetails();
return cropdetails.stream().collect(Collectors.groupingBy(CropDetailDto::getCropName, Collectors.groupingBy(
v -> v.getVarietyName() == null ? "undefined" : v.getVarietyName(),
Collectors.groupingBy(m -> m.getSubVarietyName() == null ? "undefined" : m.getSubVarietyName()))));
}
我以某种方式能够以这种格式表示数据。
{
"Tomato": {
"Red Tomato": {
"Red Tomato 1 quality": [
{
"cropName": "Tomato",
"varietyName": "Red Tomato",
"subVarietyName": "Red Tomato 1 quality",
"varietyId": 1002,
"cropId": 1,
"subVarietyId": 1003 //cropDetailDto is again represented
//at the leaf level
}
],
"Red Tomato 2 quality": [
{
"cropName": "Tomato",
"varietyName": "Red Tomato",
"subVarietyName": "Red Tomato 2 quality",
"varietyId": 1002,
"cropId": 1,
"subVarietyId": 1004
}
]
}
},
"Brinjal": {
"undefined": {
"undefined": [
{
"cropName": "Brinjal",
"varietyName": null,
"subVarietyName": null,
"varietyId": null,
"cropId": 8,
"subVarietyId": null
}
]
}
}
}
但是,此表示形式以
undefined
作为键,因为它为空键抛出了NPE。我想以更简洁的格式表示相同的数据。
像这样:
{
"Tomato": {
"Red Tomato": [
"Red Tomato 1 quality",
"Red Tomato 2 quality"
]
},
"Brinjal": {}
}
即
如果有一个空键,我希望它移至下一个条目。
我最近开始使用Java 8,我正在寻找一种简洁的方法来实现上述结构。
CropDetailDto:
public interface CropDetailDto {
Long getCropId();
String getCropName();
Long getVarietyId();
String getVarietyName();
Long getSubVarietyId();
String getSubVarietyName();
}
结果返回类型也可以是简单的
HashMap<String, Object>
。另外,如果无法使用Java 8功能实现此功能,请提供一种无需Java 8即可实现此功能的方法。
提前致谢。
最佳答案
您可以使用Collectors.mapping()
代替最后一个Collectors.groupingBy()
:
public Map<String, Map<String, List<String>>> findCropDetails() {
List<CropDetailDto> cropdetails = cropRepository.getCropDetails();
return cropdetails.stream().collect(Collectors.groupingBy(CropDetailDto::getCropName,
Collectors.groupingBy(v -> v.getVarietyName() == null ? "undefined" : v.getVarietyName(),
Collectors.mapping(m -> m.getSubVarietyName() == null ? "undefined" : m.getSubVarietyName(),
Collectors.toList()))));
}
这将返回以下地图:
{
"Tomato": {
"Red Tomato": [
"Red Tomato 1 quality",
"Red Tomato 2 quality"
]
},
"Brinjal": {
"undefined": [
"undefined"
]
}
}
要从结果中删除
null
值,可以使用Collectors.filtering()
并稍微修改上面的代码:public Map<String, Map<String, List<String>>> findCropDetails() {
List<CropDetailDto> cropdetails = cropRepository.getCropDetails();
return cropdetails.stream().collect(Collectors.groupingBy(CropDetailDto::getCropName,
Collectors.filtering(v -> v.getVarietyName() != null, Collectors.groupingBy(CropDetailDto::getVarietyName,
Collectors.filtering(m -> m.getSubVarietyName() != null, Collectors.mapping(CropDetailDto::getSubVarietyName,
Collectors.toList()))))));
}
使用此最终结果将如下所示:
{
"Tomato": {
"Red Tomato": [
"Red Tomato 1 quality",
"Red Tomato 2 quality"
]
},
"Brinjal": {}
}