How do you convert this into a Java 8 lambda expression?
List<String> inputStrings = new ArrayList<>(); // say, a list of inputStrings
ArrayList<SomeClass> outputResultStrings = new ArrayList();
for(String anInputString : inputStrings) {
SomeClass someResult = doSomthing(anInputString);
if (someResult != null) {
outputResultStrings.add(someResult);
}
}
Your code essentially loops over the input strings, performs doSomthing
on each of them (map
in Java's terminology), ignores the results that are null
(filter
in Java's terminology) and then produces a list of those results (collect
in Java's terminology). And when you put it all together:
List<SomeClass> outputResultStrings =
inputStrings.stream()
.map(SomeClass::doSomething)
.filter(x -> x != null)
.collect(Collectors.toList());
EDIT:
As suggested by Tunaki, the not-null check can be cleaned up with Objects::nonNull
:
List<SomeClass> outputResultStrings =
inputStrings.stream()
.map(SomeClass::doSomething)
.filter(Objects::nonNull)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With