I have a map which consists of key as code. I need to pass these map objects and retrieve products which matches this code. I achieved this scenario using loops but I want to know how to implement same using stream and map in java.
code implemented using loops:
List<ProductModel> models=new ArrayList<>();
for(Map.Entry<String, String> entry:entries)
{
ProductModel product=getProductService().getProductForCode(entry.getValue());
models.add(product);
}
Please help me in implementing above logic using map and streams in java
CodePudding user response:
You can use collect function of stream something like below, entry is your original map which has String as key & value:
List<ProductModel> models= entry.values().stream().
collect(ArrayList<ProductModel>::new, (x, y) -> x.add(getProductService().
getProductForCode(y)), ArrayList::addAll);
Or alternatively :
List<ProductModel> models=
entry.values().stream().map(x -> getProductService().getProductForCode(x)).
collect(Collectors.toList());
CodePudding user response:
I hope the below code will helps
List<ProductModel> models = entry.values().stream().map(getProductService()::getProductForCode).collect(Collectors.toList());