Add items to a number of lists I am working on a rewrite project, where I'm supposed to change the
enhanced for-loop code used in java6 to the newer forEach loop.
Similarly, we have to use Streams API as heavily as possible.
Below is the complete scenario followed by code sample

Iterate over each element of List&lt;String&gt; list.
If Map&lt;String, A&gt; has each as key, take the corresponding A value from the Map.
A has an instance variable, List&lt;B&gt; which is a list of class B objects.
If List&lt;B&gt; is null initialize new List&lt;B&gt; and put some value inside it. Else just add a new value to Existing List&lt;B&gt;.

The complete code for the problem is below:
    class A{
        List&lt;B&gt; values;
    
    }
    
    class B{
    
    }
    
    //Assume some values
    List&lt;String&gt; list = [&quot;val1&quot;,&quot;val2&quot;];
    //Assume some values
    Map&lt;String, A&gt; map = { &quot;val1&quot; : [A object] , &quot;val2&quot; : [A object] };
    B b = new B();
    
    //Iterate over every value in list
    for(String each: list){
        //if map has a key with the value inside the list
        A a = map.get(each);
    
        //A has a list called &quot;values&quot; of B class objects. If that list is not null or empty add a new B object (b )in our case to the a List else initialze a new List and add the value there.
        if(a.values != null &amp;&amp; !a.values.isEmpty()){
            a.values.add(b);
        }else{
            List&lt;B&gt; bList = new ArrayList&lt;&gt;();
            bList.add(b);
            a.values = bList;
        }
    }
Non sure what is the purpose to write your code in a java 8 way, please explain this part.

I think you mean using streams.

Anyway, here is an example.

Comparing with your code I introduced a filter that guarantee the key in list exists as a key in the map.

The other part are equivalent.

UPDATE: I added the _map_part that I had forgot previously.
The map can transform your list of string in a new list of different types.

In this case you use the list of string as a filter to get elements from the map. You don't want to operate on the String keys, instead you want to access the map values that are objects of type A.

list.stream()
    .filter(key -&gt; (map.containsKey(key)))
    .map(key -&gt; (map.get(key)))
    .forEach(a -&gt; {
         if (a.values == null)
             a.values = new ArrayList&lt;&gt;();

         a.values.add(b);
     });


I think the main difference for this approach, compared with the old fashion is that you describe more your intentions, and the purpose of the code emerges much clearly.

But in trivial examples like yours the differences are not so clear and the functional approach seems much complicated.

Not all the case can be converted properly in this way, there are still cases where you whould prefer the loop over the streams.