Monday 16 May 2022

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<arr.length; 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 < list.size(); 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<Integer> list = Arrays.asList(2, 3, 5, 7);
		
		for(Integer ele: list) {
			System.out.println(ele);
		}
		
		for(int i = 0; i < list.size(); 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<Integer, String> 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 EvenIndicesList<T> implements Iterable<T> {
	private List<T> list;

	EvenIndicesList(List<T> list) {
		this.list = list;
	}

	public Iterator<T> iterator() {
		return new EvenIterator<T>();
	}

	@SuppressWarnings("hiding")
	private class EvenIterator<T> implements Iterator<T> {
		int size = list.size();
		int currentPointer = 0;

		public boolean hasNext() {
			return (currentPointer < size);
		}

		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<Integer> list = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19);

		EvenIndicesList<Integer> 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

No comments:

Post a Comment