How do I iterate over a stream in Java using for? [duplicate]

You need an iterable to be able to use a for-each loop, for example a collection or an array:

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

Alternatively, you could completely get rid of the for loop:

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

You mention you don’t want to refactor your for loop but you could extract its body in another method:

strings.stream().filter(s->s.length() == 2).forEach(this::process);

private void process(String s) {
  //body of the for loop
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)