Issue
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.
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
Solution
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());
Answered By - Ashish Patil
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)