Open In App

For-each loop in Java

Last Updated : 16 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
 

Prerequisite: Decision making in Java
For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. 
 

  • It starts with the keyword for like a normal for-loop.
  • Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
  • In the loop body, you can use the loop variable you created rather than using an indexed array element. 
     
  • It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)

Syntax: 

for (type var : array) 
{ 
    statements using var;
}

Simple program with for each loop:

Java




/*package whatever //do not write package name here */
  
import java.io.*;
  
class Easy
  
{
  
    public static void main(String[] args)
  
    {
  
        // array declaration
  
        int ar[] = { 10, 50, 60, 80, 90 };
  
        for (int element : ar)
  
            System.out.print(element + " ");
    }
}


Output

10 50 60 80 90 

The above syntax is equivalent to: 

for (int i=0; i<arr.length; i++) 
{ 
    type var = arr[i];
    statements using var;
}

Java




// Java program to illustrate 
// for-each loop
class For_Each     
{
    public static void main(String[] arg)
    {
        {
            int[] marks = { 125, 132, 95, 116, 110 };
              
            int highest_marks = maximum(marks);
            System.out.println("The highest score is " + highest_marks);
        }
    }
    public static int maximum(int[] numbers)
    
        int maxSoFar = numbers[0];
          
        // for each loop
        for (int num : numbers) 
        {
            if (num > maxSoFar)
            {
                maxSoFar = num;
            }
        }
    return maxSoFar;
    }
}


Output

The highest score is 132

Limitations of for-each loop 
       decision-making

  1. For-each loops are not appropriate when you want to modify the array:
     
for (int num : marks) 
{
    // only changes num, not the array element
    num = num*2; 
}

       2. For-each loops do not keep track of index. So we can not obtain array index using For-Each loop 
 

for (int num : numbers) 
{ 
    if (num == target) 
    {
        return ???;   // do not know the index of num
    }
}

        3.  For-each only iterates forward over the array in single steps 
 

// cannot be converted to a for-each loop
for (int i=numbers.length-1; i>0; i--) 
{
      System.out.println(numbers[i]);
}

        4. For-each cannot process two decision making statements at once 
 

// cannot be easily converted to a for-each loop 
for (int i=0; i<numbers.length; i++) 
{
    if (numbers[i] == arr[i]) 
    { ...
    } 
}

        5. For-each also has some performance overhead over simple iteration: 

Java




/*package whatever //do not write package name here */
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main (String[] args) {
        List<Integer> list = new ArrayList<>();
        long startTime;
        long endTime;
        for (int i = 0; i < 1000000; i++) {
            list.add(i);
        }
        // Type 1
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int i : list) {
            int a = i;
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("For each loop :: " + (endTime - startTime) + " ms");
          
        // Type 2
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int j = 0; j < list.size(); j++) {
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms");
          
        // Type 3
        startTime = Calendar.getInstance().getTimeInMillis();
        int size = list.size();
        for (int j = 0; j < size; j++) {
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("By calculating collection.size() first :: " + (endTime - startTime) + " ms");
      
        // Type 4
        startTime = Calendar.getInstance().getTimeInMillis();
        for(int j = list.size()-1; j >= 0; j--) {
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using [int j = list.size(); j > size ; j--] :: " + (endTime - startTime) + " ms");
    }
}
  
// This code is contributed by Ayush Choudhary @gfg(code_ayush)


Output

For each loop :: 45 ms
Using collection.size() :: 11 ms
By calculating collection.size() first :: 13 ms
Using [int j = list.size(); j > size ; j--] :: 15 ms

Related Articles: 
For-each in C++ vs Java 
Iterator vs For-each in Java

 



Previous Article
Next Article

Similar Reads

Difference Between for loop and Enhanced for loop in Java
Java for-loop is a control flow statement that iterates a part of the program multiple times. For-loop is the most commonly used loop in java. If we know the number of iteration in advance then for-loop is the best choice. Syntax: for( initializationsection ; conditional check ; increment/decrement section) { // Code to be executed } Curly braces i
5 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list. Create an empty list t
3 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened. Create an empty list to c
3 min read
Java do-while loop with Examples
Loops in Java come into use when we need to repeatedly execute a block of statements. Java do-while loop is an Exit control loop. Therefore, unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Syntax: do { // Loop Body Update_expression } // Condition check while (test_expression); Note: The
5 min read
Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer one. Working: The first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. A break within either the inner or outer loop would i
2 min read
Generic For Loop in Java
When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes. In normal for loop, we write three statements : for( statement1; statement 2
4 min read
String Array with Enhanced For Loop in Java
Enhanced for loop(for-each loop) was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing arrays or collections. This loop also makes the code more readable and r
1 min read
For Loop in Java
Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Let us understand Java for loop with
7 min read
Java while loop with Examples
Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. While loop in Java comes into use when we need to repeatedly execute a block of statements. The while loop is considered as a repeating if statement. If the number o
4 min read
Infinite Loop Puzzles in Java
Problem 1 : Insert code in the given code segments to make the loop infinite. class GFG { public static void main(String s[]){ /* Insert code here */ for (int i = start; i &lt;= start + 1; i++) { /* Infinite loop */ } } } Solution: It looks as though it should run for only two iterations, but it can be made to loop indefinitely by taking advantage
3 min read
How to Loop Over TreeSet in Java?
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.  Now the task
4 min read
Difference between while and do-while loop in C, C++, Java
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax : while (boolean condition){ loop statements...}Flowchart: Example: [GFGTABS] C++ #include &lt;iostream&gt; using namespace std; int main() { int i =
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
While loop with Compile time constants
While loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. It is mostly used in situations where the exact number of iterations beforehand. Below is the image to illustrate the while loop: Syntax: while(test_expression){ // state
6 min read
Retrieving Elements from Collection in Java (For-each, Iterator, ListIterator &amp; EnumerationIterator)
Prerequisite: Collection in Java Following are the 4 ways to retrieve any elements from a collection object: For-each For each loop is meant for traversing items in a collection. // Iterating over collection 'c' using for-each for (Element e: c) System.out.println(e); We read the ‘:’ used in for-each loop as “in”. So loop reads as “for each element
3 min read
Extracting each word from a String using Regex in Java
Given a string, extract words from it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Funny?? are not you? Output : Funny are not you Input : Geeks for geeks?? Output : Geeks for geeks We have discussed a solution for C++ in this post : Program to extract word
2 min read
Get the first letter of each word in a string using regex in Java
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extract the first letter of each word. It uses '/b'(on
1 min read
Check whether two Strings are Anagram of each other using HashMap in Java
Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an Anagram of each other. Approach: Hashmaps can be used to determine if two given strings are anagrams
3 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Print number of words, vowels and frequency of each character
Given a string str with uppercase, lowercase and special characters. The input string is to end with either a space or a dot. The problem is to calculate the number of words, vowels and frequency of each character of the string in a separate line. Example : Input : How Good GOD Is. Output : Number of words = 4 Number of vowels = 5 Number of upper c
8 min read
Modify a Circular Doubly Linked List such that each node stores the sum of all nodes except itself
Given a circular doubly linked list consisting of N nodes, the task is to modify every node of the given Linked List such that each node contains the sum of all nodes except that node. Examples: Input: 4 ↔ 5 ↔ 6 ↔7 ↔ 8Output: 26 ↔ 25 ↔ 24 ↔ 23 ↔ 22Explanation:1st Node: Sum of all nodes except itself = (5 + 6 + 7 + 8) = 26.2nd Node: Sum of all nodes
15+ min read
Sum of leaf nodes at each horizontal level in a binary tree
Given a Binary Tree, the task is to find the sum of leaf nodes at every level of the given tree. Examples: Input: Output:0063012Explanation:Level 1: No leaf node, so sum = 0Level 2: No leaf node, so sum = 0Level 3: One leaf node: 6, so sum = 6 Level 4: Three leaf nodes: 9, 10, 11, so sum = 30Level 5: One leaf node: 12, so sum = 12 Input: Output:006
14 min read
Generate an Array by multiplying each element of given Array by K
Given an array arr[] of size N and an integer K. The task is to multiply each element of the array by K. Examples : Input: arr[] = { 3, 4 }, K = 2Output: 6 8Explanation: The elements become 3*2 = 6 and 4*2 = 8. Input: arr[] = { 0, 1, 2 }, K = 7Output: { 0, 7, 14 } Approach: The given problem can be solved using the following steps : Iterate through
6 min read
How Eureka Server and Client Communicate with Each Other in Microservices?
Service Discovery is one of the major things of a microservice-based architecture. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly functional, with each server copying the state of the registered services to the others. In the previous article, we have seen How to Register Microservi
5 min read
Check if two arrays are permutations of each other
Given two unsorted arrays of the same size, write a function that returns true if two arrays are permutations of each other, otherwise false. Examples: Input: arr1[] = {2, 1, 3, 5, 4, 3, 2} arr2[] = {3, 2, 2, 4, 5, 3, 1}Output: YesInput: arr1[] = {2, 1, 3, 5,} arr2[] = {3, 2, 2, 4}Output: NoWe strongly recommend you to minimize your browser and try
15+ min read
Print first letter of each word in a string using regex
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeksOutput :Gfg Input : United KingdomOutput : UKBelow is the Regular expression to extract the first letter of each word. It uses '/b'(one o
3 min read
Count ways to reach end from start stone with at most K jumps at each step
Given N stones in a row from left to right. From each stone, you can jump to at most K stones. The task is to find the total number of ways to reach from sth stone to Nth stone. Examples: Input: N = 5, s = 2, K = 2 Output: Total Ways = 3 Explanation: Assume s1, s2, s3, s4, s5 be the stones. The possible paths from 2nd stone to 5th stone: s2 -&gt; s
7 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Article Tags :
Practice Tags :