java break out of stream foreach code example

Example 1: break a java stream foreach

Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck")
  	.takeWhile(n -> n.length() % 2 != 0)
  	.forEach(System.out::println);

//sysout -> cat
//sysout -> dog

//Same code, no streams

List<String> list = asList("cat", "dog", "elephant", "fox", "rabbit", "duck");
for (int i = 0; i < list.size(); i++) {
    String item = list.get(i);
    if (item.length() % 2 == 0) {
        break;
    }
    System.out.println(item);
}

Example 2: foreach skip to next java

for(String str : strArr) {
	continue; //Skips current iteration and moves onto the following 
}

Tags:

Php Example