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


how convert java 8 lambda expression?

list<string> inputstrings = new arraylist<>(); // say, list of inputstrings  arraylist<someclass> outputresultstrings = new arraylist(); for(string aninputstring : inputstrings) {     someclass someresult = dosomthing(aninputstring);     if (someresult != null) {         outputresultstrings.add(someresult);     } } 

your code loops on input strings, performs dosomthing on each of them (map in java's terminology), ignores results null (filter in java's terminology) , produces list of results (collect in java's terminology). , when put together:

list<someclass> outputresultstrings =      inputstrings.stream()                 .map(someclass::dosomething)                 .filter(x -> x != null)                 .collect(collectors.tolist()); 

edit:
suggested tunaki, not-null check can cleaned objects::nonnull:

list<someclass> outputresultstrings =      inputstrings.stream()                 .map(someclass::dosomething)                 .filter(objects::nonnull)                 .collect(collectors.tolist()); 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -