Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a loop that sometimes adds a transformed value to a Java 8 stream/lambda?

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);
    }
}
like image 648
ikevin8me Avatar asked Dec 25 '22 10:12

ikevin8me


1 Answers

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());
like image 68
Mureinik Avatar answered Dec 26 '22 22:12

Mureinik