I have this code:
List<String> strings = Arrays.asList("a", "b", "cc");
for (String s : strings) {
if (s.length() == 2)
System.out.println(s);
}
I want to write it using a filter and a lambda:
for (String s : strings.stream().filter(s->s.length() == 2)) {
System.out.println(s);
}
I get Can only iterate over an array or an instance of java.lang.Iterable
.
I try:
for (String s : strings.stream().filter(s->s.length() == 2).iterator()) {
System.out.println(s);
}
And I get the same error. Is this even possible? I would really prefer not to do stream.forEach() and pass a consumer.
Edit: it's important to me not to copy the elements.