Class Package{
Long packageId;
String packageName;
List<Service> serviceList;
}
Class Service{
Long serviceId;
String location;
}
List <Package> packageList
Above there are my classes and the requirement is to collect packageId from the outer list packageList and serviceId from the inner list (the Services of each Package) where packageList.packageName == "Full" and serviceList.location == "Japan". Also, I need to know whether that kind of record exist or not. This is what I've written so far collecting the data into a HashMap.
HashMap<String,Object> stringObjectHashMap = new HashMap<>();
boolean isFound = packageList.stream()
.filter(package -> "Full".equalsIgnoreCase(package.getPackageName()))
.peek(package ->stringObjectHashMap.put("packageId",package.getPackageId()))
.flatMap(package -> package.getServiceList().stream())
.filter(service -> service.getLocation().equalsIgnoreCase("Japan"))
.peek(service -> stringObjectHashMap.put("serviceId",service.getServiceId()))
.anyMatch(service -> service.getLocation().equalsIgnoreCase("Japan"));
The problem is that Sonar complains about the use of peek() inside the stream. It says "According to its JavaDocs, the intermediate Stream operation java.util.Stream.peek() “exists mainly to support debugging” purposes."
Can anyone suggest a better solution?
sample input:
[
{
"packageId": 13,
"packageName": "Normal",
"serviceList": [
{
"serviceId": "100",
"location": "China"
}
]
},
{
"packageId": 10,
"packageName": "Full",
"serviceList": [
{
"serviceId": "100",
"location": "Spain"
}
]
},
{
"packageId": 5,
"packageName": "Full",
"serviceList": [
{
"serviceId": "100",
"location": "Japan"
}
]
}
]
expected output,
"packageId": 5 //this is from outer list
"serviceId": 100 //this is from inner list
Note: "Full" package can appear multiple times. As well as location "Japan" also can appear multiple times in services. But a combination of the packageName with a value "Full" and location "Japan" can appear only once.