I have three classes: product, customer and application.
The schema of these classes are as follows:
class application {
String productID;
String customerID;
String applicationId;
String name;
....
// getters and setters and associated constructors
}
class product {
String name;
String ID;
...
// constructors and getters and setters
}
class customer {
String name;
String ID;
...
// constructors and getters and setters
}
The only way of connection between product and customer is through the application.
The problem in hand is to retrieve all products with their associated customers (appID and customerID) in this JSON format.
[
{
"product": {
// product details
}
"customers": [ {
"application": <value_appID>,
"ID": <value_customerID> } ]
}
]
I have done this using a nested for loop:
for (Product product : products) {
ProductInfo prodInfo = new
ProductInfo();
prodInfo.setProduct(product);
List<CustomerInfo> associatedCustomerList = new ArrayList<>();
for (Object res : searchResults.getResult()) {
if ((product.getId()).equals((String) ((Map) res).get("productID"))) {
CustomerInfo associatedCustomer = new CustomerInfo();
associatedCustomer.setCustomerID((String) ((Map) res).get("customerID"));
associatedCustomer.setApplicationId((String) ((Map) res).get("appId"));
associatedCustomerList.add(associatedCustomer);
}
prodInfo.setCustomers(associatedCustomerList);
}
productInfo.add(prodInfo);
}
Here, searchResults
contain the result from List<? extends Object>
. CustomerDetails
contain appId
and customerId
as attributes. ProductInformationWithAssociatedCustomer
is the response class.
Furthermore, I have converted this into the following which utilizes Java 8 Stream API:
List<ProductInfo> prodList = products.stream()
.map(product -> {
List<CustomerInfo> customerList =searchResults.getResult().stream()
.filter(searchResult -> (product.getId()).equals((String) ((Map) searchResult).get("productID")))
.map(searchResult -> new CustomerInfo((String) ((Map) searchResult).get("customerID"),(String) ((Map) searchResult).get("appId")))
.collect(Collectors.toList());
return new ProductInfo(product, customerList);
}).collect(Collectors.toList());
This code is working fine.
The questions I have are:
Am I making correct/ optimal use of Java 8 stream features?
Provided, I want to do it using Java 8 Stream APIs only, should I do it in any better way?
What are the factors I need to consider while optimizing this type of codes.