Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
In Java, the foreach
loop, also known as the enhanced for
loop, is a simplified syntax for iterating through elements in a collection or an array. The foreach
loop is easier to use and less error-prone compared to traditional for
loops or Iterator
objects.
Let's see how to use the foreach
loop to traverse various collections in Java:
public class Main { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; for (int number : numbers) { System.out.println(number); } } }
List
:import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("John"); names.add("Alice"); names.add("Bob"); for (String name : names) { System.out.println(name); } } }
Set
:import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { Set<String> colors = new HashSet<>(); colors.add("Red"); colors.add("Green"); colors.add("Blue"); for (String color : colors) { System.out.println(color); } } }
Map
using its entrySet
:import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<String, Integer> ages = new HashMap<>(); ages.put("John", 25); ages.put("Alice", 30); ages.put("Bob", 22); for (Map.Entry<String, Integer> entry : ages.entrySet()) { System.out.println(entry.getKey() + " is " + entry.getValue() + " years old"); } } }
Map
using its keySet
and get
method:import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<String, Integer> ages = new HashMap<>(); ages.put("John", 25); ages.put("Alice", 30); ages.put("Bob", 22); for (String name : ages.keySet()) { System.out.println(name + " is " + ages.get(name) + " years old"); } } }
In conclusion, the foreach
loop in Java provides a simple and efficient way to traverse collections and arrays. It is easier to use and less error-prone compared to traditional for
loops or Iterator
objects. You can use the foreach
loop with various collection types, including List
, Set
, and Map
, to iterate through their elements.
Traversing collections with foreach loop in Java: The foreach loop simplifies iterating over elements in a collection.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); for (String name : names) { System.out.println(name); }
Using enhanced for loop with ArrayList in Java: ArrayLists can be easily traversed using the enhanced for loop.
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); for (int num : numbers) { System.out.println(num); }
Iterating over arrays with foreach loop in Java: Arrays can also be traversed using the foreach loop.
int[] array = {10, 20, 30, 40, 50}; for (int value : array) { System.out.println(value); }
Java foreach loop vs traditional for loop: The foreach loop simplifies syntax and is more readable than the traditional for loop.
// Traditional for loop for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } // Foreach loop for (int value : array) { System.out.println(value); }
Working with Set and Map using foreach loop in Java: Sets and Maps can be iterated using the foreach loop.
Set<String> set = new HashSet<>(Arrays.asList("apple", "orange", "banana")); for (String fruit : set) { System.out.println(fruit); }
Map<String, Integer> map = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }
Iterating through a LinkedList with foreach loop in Java: LinkedLists can be traversed using the foreach loop.
LinkedList<Double> prices = new LinkedList<>(Arrays.asList(10.5, 20.0, 15.75)); for (double price : prices) { System.out.println(price); }
Custom classes and foreach loop in Java:
Custom classes can be iterated using the foreach loop if they implement the Iterable
interface.
public class MyCollection implements Iterable<String> { private List<String> items = new ArrayList<>(); public void addItem(String item) { items.add(item); } @Override public Iterator<String> iterator() { return items.iterator(); } } // Usage MyCollection collection = new MyCollection(); collection.addItem("Item 1"); collection.addItem("Item 2"); for (String item : collection) { System.out.println(item); }
Multidimensional arrays and foreach loop in Java: Multidimensional arrays can be traversed using nested foreach loops.
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; for (int[] row : matrix) { for (int value : row) { System.out.print(value + " "); } System.out.println(); }
Java foreach loop and Iterable interface:
The foreach loop can iterate over classes that implement the Iterable
interface.
public class MyIterable implements Iterable<Integer> { private List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); @Override public Iterator<Integer> iterator() { return numbers.iterator(); } } // Usage MyIterable iterable = new MyIterable(); for (int num : iterable) { System.out.println(num); }
Using forEach() method with collections in Java:
Java 8 introduced the forEach
method for collections, providing a concise way to iterate.
List<String> colors = Arrays.asList("Red", "Green", "Blue"); colors.forEach(color -> System.out.println(color));
Java streams and foreach loop for collection processing: Streams provide powerful features for processing collections in Java.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); numbers.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println);
Exception handling in foreach loop in Java: Exception handling within a foreach loop can be achieved with a try-catch block.
List<String> data = Arrays.asList("1", "2", "three", "4"); for (String str : data) { try { int num = Integer.parseInt(str); System.out.println(num); } catch (NumberFormatException e) { System.err.println("Invalid number format: " + str); } }
Lambda expressions and foreach loop in Java 8+: Lambda expressions can be used to further simplify the syntax of foreach loops.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.forEach(name -> System.out.println(name));