+ 1
for each && for
when do we use for each instead of for?
2 Answers
+ 5
For loop allows you to modify elements in an array but for each loop doesn't since it is only meant for traversing.
Also you need to set an index in for loop to access elements and it enables random access of elements possible but you cannot do that with for each loop.
For each loop is faster and efficient when it comes to large sets of data.
+ 6
String[] array=//arrays of strings
normal foreach,
- for(String str:array){
System.out.print(str);
}
Stream foreach,
-Arrays.stream(arr).forEach(i - > System.out.print(i));