Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How for-each or enhanced for loop works in Java?

In this post, I am going to explain about for-each loop.

 

‘for-each’ is an enhanced version of for loop and provides a cleaner way to iterate over collections and arrays.

 

Let’s get comfortable by practising some examples.

 

Iterate over an array using for-each loop

Syntax

for (DataType ele : array) { 
.....
.....
}

 

Above snippet is equivalent to below ‘for’ loop version.

for (int i=0; i{ 
DataType ele = arr[i];
.......
.......
}

 

IterateOverArrayUsingForEachLoop.java

package com.sample.app;

public class IterateOverArrayUsingForEachLoop {

public static void main(String[] args) {
int[] arr = { 2, 3, 5, 7 };

for (int ele : arr) {
System.out.println(ele);
}
}

}

 

Output

2
3
5
7

 

Iterate over an List using for-each loop

Syntax

 

for (DataType ele : list) { 
.....
.....
}

 

Above snippet is equivalent to below ‘for’ loop version.

for(int i = 0; i 	DataType ele = list.get(i);
......
......
}

Find the below working application.

 

IterateOverListUsingForEachLoop.java

package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class IterateOverListUsingForEachLoop {
public static void main(String[] args) {
List list = Arrays.asList(2, 3, 5, 7);

for(Integer ele: list) {
System.out.println(ele);
}

for(int i = 0; i System.out.println(list.get(i));
}
}
}

Iterate over a map using for-each loop

Syntax

for(DataType key: map.keySet()) {
DataType valye = map.get(key);
.....
.....
}

Find the below working application.

 

IterateOverAMapUsingForEachLoop.java

package com.sample.app;

import java.util.HashMap;
import java.util.Map;

public class IterateOverAMapUsingForEachLoop {

public static void main(String[] args) {
Map numbersMap = new HashMap();

numbersMap.put(1, "One");
numbersMap.put(2, "Two");
numbersMap.put(3, "Three");

for(Integer key: numbersMap.keySet()) {
System.out.printf("%d --> %s\n", key, numbersMap.get(key));
}
}

}

Output

1 --> One
2 --> Two
3 --> Three

You can refer this post, to find different ways to iterate over a map using for-each loop.

 

Can I provide for-each behaviour to custom collection?

By implementing Iterable interface, we can provide for-each behaviour to a custom collection.

 

EvenIndicesList.java

package com.sample.app;

import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class EvenIndicesListT> implements IterableT> {
private List list;

EvenIndicesList(List list) {
this.list = list;
}

public Iteratoriterator() {
return new EvenIterator();
}

@SuppressWarnings("hiding")
private class EvenIteratorT> implements IteratorT> {
int size = list.size();
int currentPointer = 0;

public boolean hasNext() {
return (currentPointer }

public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}

@SuppressWarnings("unchecked")
T val = (T) list.get(currentPointer);
currentPointer += 2;

return val;
}

}

}

‘EvenIndicesList’ class print the elements at even indexes while iterate using for-each loop. Let’s test this behaviour.

 

TestEvenList.java

package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class TestEvenList {
public static void main(String args[]) {
List list = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19);

EvenIndicesList myList = new EvenIndicesList(list);

for (int i : myList) {
System.out.println(i);
}
}
}

Output

2
5
11
17


 

 You may like

Interview Questions

Jagged arrays in Java

Get the length of longest row in a two dimensional jagged array in Java

Quick guide to OutOfMemoryError in Java

StackOverFlowError vs OutOfMemoryError in Java

Different ways to iterate over a map using for-each loop



This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

How for-each or enhanced for loop works in Java?

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×