foreach - How do I iterate over a stream in Java using for? -


this question has answer here:

i have code:

list<string> strings = arrays.aslist("a", "b", "cc"); (string s : strings) {     if (s.length() == 2)         system.out.println(s); } 

i want write using filter , lambda:

for (string s : strings.stream().filter(s->s.length() == 2)) {     system.out.println(s); } 

i can iterate on array or instance of java.lang.iterable.

i try:

for (string s : strings.stream().filter(s->s.length() == 2).iterator()) {     system.out.println(s); } 

and same error. possible? prefer not stream.foreach() , pass consumer.

edit: it's important me not copy elements.

you need iterable able use for-each loop, example collection or array:

for (string s : strings.stream().filter(s->s.length() == 2).toarray(string[]::new)) { 

alternatively, rid of loop:

strings.stream().filter(s->s.length() == 2).foreach(system.out::println); 

you mention don't want refactor loop extract body in method:

strings.stream().filter(s->s.length() == 2).foreach(this::process);  private void process(string s) {   //body of loop } 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -