foreach – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sat, 24 Sep 2022 08:04:07 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg foreach – Programmerbay https://programmerbay.com 32 32 Difference between For and For-each Loop in Java https://programmerbay.com/difference-between-for-and-for-each-loop/ https://programmerbay.com/difference-between-for-and-for-each-loop/#respond Sat, 06 Aug 2022 09:11:36 +0000 https://www.programmerbay.com/?p=4477 A loop is a control statement which executes a particular block of code repeatedly until a given condition becomes false. There are various types of loops such as while, do-while and for loop.

In this article, we will be focusing on for loop and its enhanced version.

for loop and for each loop in java

If you’re looking for forEach method introduced in Java 8: ForEach Method in Java 8

Difference between For and For-each Loop in Java

For LoopForeach Loop
It uses an index of an element to fetch data from an arrayIt uses an iteration variable to automatically fetch data from an array
Termination of this traditional loop is controlled by loop condition. Therefore, For loop executes repeatedly until the given condition turns out to be falseNo such provision is provided in foreach, instead break statement can be used to terminate the execution of the loop early, otherwise, it executes until the last element gets evaluated
It requires loop counter, initial and end values, in order to iterate through all the elements of an arrayIt automates the iteration by using the iteration variable which stores one element each time
When we iterate through using traditional for loop we can manipulate the actual data of an arrayThe iteration variable in foreach is read-only. It means changes made on iteration value would not affect the actual data of the collection or array
It was introduced in Java 1It was introduced back in Java 5
It has the flexibility of the iterating an array whether it is increasing order or decreasing orderIt can iterate only in a linear manner from initial to end element, but not vice versa
Syntax:
for( initialization; condition; iteration)
{
// body
}
Syntax:
for(type var_name: collection)
{
// body
}
It works only on indexable objects where random access of elements are allowed It works on all indexable objects even when random access of an individual element is not allowed

Traditional For loop in Java

It is generally known as a traditional for loop.
In Java, “for loop” is used to execute a particular block of code a fixed number of times. In other words, when the number of iterations are already known, then it is typically used.

It provides compact looping structure as initialization, condition and iteration are put together within a single statement.
Like C++, a simple for loop comprises three parts, initialization, condition and increment/decrement

1. Initialization: In this, a counter or control variable is assigned with some value and acts as a base for the loop counter
2. Condition: It is a relational or logical expression that returns a boolean value, true or false. It is evaluated after each iteration and continues execution until the condition turns out to be false.
3. Increment/ decrement: It updates with each iteration with incremented or decremented values

.

Syntax : 

for(initialization;condition; updatableExp){
//loop body
}

For each loop in Java

For each is the enhanced for loop which was introduced in Java 5. It is used to iterate through a collection of objects.

Unlike traditional for loop, the enhanced loop isn’t declared with control variable, condition, and increment/decrement, instead, an element of the same array or list type needs to be declared with a colon, is followed by the list or array name.

It executes until all the elements in the list are traversed.

Syntax:

for (type element : list/array)
{
// loop body
}

Java program to show the working of for loop

Program:

public class ForLoopExample {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList();
        list.add(5);
        list.add(9);
        list.add(7);
        list.add(65);
        list.add(4);
        list.add(0);

        for(int i=0;i<list.size();i++)
        {
            System.out.println("List items : "+list.get(i));
        }
    }

}

Output:

List items : 5
List items : 9
List items : 7
List items : 65
List items : 4
List items : 0

Java program to show the working of for-each (enhanced for loop ) loop

public class ForLoopExample {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList();
        list.add(5);
        list.add(9);
        list.add(7);
        list.add(65);
        list.add(4);
        list.add(0);

        for (Integer value: list
             ) {
            System.out.println("Items : "+value);
        }
    }

}

Output:

Items : 5
Items : 9
Items : 7
Items : 65
Items : 4
Items : 0

]]>
https://programmerbay.com/difference-between-for-and-for-each-loop/feed/ 0
ForEach in Java 8 with Example https://programmerbay.com/foreach-method-in-java-8/ https://programmerbay.com/foreach-method-in-java-8/#respond Wed, 17 Jun 2020 10:57:02 +0000 https://programmerbay.com/?p=6435 In Java 8, forEach is introduced that provides an efficient way to iterate through collections ( List, Sets, and more) and Streams.

In Collection hierarchy, the iterable interface is the root interface in which a new feature has added namely forEach(). It allows iterating a collection of elements until the last element is processed.

It accepts consumer (functional interface) as an argument, meaning one needs to define a lambda expression that would take a single input and return nothing.

default void forEach(Consumer<? super T> action)

Functionality wise, forEach and enhanced for-loop are similar, but the new forEach is a type of internal loop. Meaning, the iterator handles iteration behind the scene, as a result, programmers don’t have to worry about the iteration behaviour.

Code Example:

Iterating over List:

import java.util.List;

public class ForEachExample {
public static void main(String[] args) {
List nameList = new ArrayList();
nameList.add("Programmer");
nameList.add("ProgrammerBay");
nameList.add("coders");

nameList.forEach(singleItem -> System.out.println(singleItem));
}
}

Output

Programmer
ProgrammerBay
coders

Iterating over Map:

import java.util.*;

public class ForEachExample {
public static void main(String[] args) {
Map nameList = new LinkedHashMap();
nameList.put(1,"Programmer");
nameList.put(2,"ProgrammerBay");
nameList.put(4,"coders");

nameList.forEach((key,value) -> System.out.println("This is my key : "+key +" and value : "+value));
}
}

 

Output:

This is my key : 1 and value : Programmer
This is my key : 2 and value : ProgrammerBay
This is my key : 4 and value : coders

Iterating over Stream of elements :

public class CreateStreams {
    public static void main(String[] args) {
        String[] stringArr = new String[]{"This", "is", "Example", "of", "Stream"};
        // Creating Stream of Array
        Stream<String> arrayStream = Stream.of(stringArr);
        arrayStream.forEach(singleString -> System.out.print(singleString + " "));
    }
}

Output:

This is Example of Stream

Point to remember about forEach:

  • Java 8, forEach is an internal loop
  • It makes code clean and more readable
  • It is less error-prone
  • It is a default method

]]>
https://programmerbay.com/foreach-method-in-java-8/feed/ 0