I have a list named inputList
from which I want to filter elements, apply a specific function to each one, and store the results in another list called outputList
. Utilizing the Stream
API introduced in Java 8, I’ve come across two methods to accomplish this. I am interested in determining which method is superior and the reasoning behind it.
Approach 1:
outputList = new ArrayList<>();
inputList.stream()
.filter(item -> item != null)
.forEach(item -> outputList.add(applyFunction(item)));
Approach 2:
outputList = inputList.stream()
.filter(item -> item != null)
.map(item -> applyFunction(item))
.collect(Collectors.toList());
I’m also open to suggestions for a potential third method.