Modify Array List using condition in Java 8 Stream API

rahulnikhare :

Could you please help me here for converting the below forEach into Stream.

Here is my code:

List<Addon> addonItems = <Some Addon List>

for (Addon addOn : addonItems) {
    if (GeoCode.TRP.toString().equals(addonItems.getSomeCode())) {
        addonItems.setName("Got from GOOGLE");
    }
}
Luke Langford :

Your example code won't actually compile but i'll attempt to answer your question...

addonItems.stream().filter(addonItem -> GeoCode.TRP.toString().equals(addonItem.getSomeCode()))
    .forEach(addonItem -> addonItem.setName("Got from GOOGLE"));

What this code does is stream the elements in the addonItems list and filter for addonItems based on our lambda filter expression. It will perform this stream operation when the forEach is called and set the name of each addonItem accordingly based on our filter expression.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=157694&siteId=1