foreach - How do I iterate over a stream in Java using for? -
this question has answer here:
- why stream<t> not implement iterable<t>? 7 answers
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
Post a Comment