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

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -