Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How does the Java 'for each' loop work?

Consider:

List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList


for (String item : someList) {
System.out.println(item);
}


What might the identical for loop look like without utilizing the for every syntax?
by

2 Answers

espadacoder11

for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
String item = i.next();
System.out.println(item);
}

Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for ( : ) idiom, since the actual iterator is merely inferred.

As was noted by Denis Bueno, this code works for any object that implements the Iterable interface.

Also, if the right-hand side of the for (:) idiom is an array rather than an Iterable object, the internal code uses an int index counter and checks against array.length instead.
sandhya6gczb
In Java 8, they introduced forEach. Using it List, Maps can be looped.

Loop a List using for each

List<String> someList = new ArrayList<String>();
someList.add("A");
someList.add("B");
someList.add("C");

someList.forEach(listItem -> System.out.println(listItem))

or

someList.forEach(listItem-> {
System.out.println(listItem);
});

Loop a Map using for each

Map<String, String> mapList = new HashMap<>();
mapList.put("Key1", "Value1");
mapList.put("Key2", "Value2");
mapList.put("Key3", "Value3");

mapList.forEach((key,value)->System.out.println("Key: " + key + " Value : " + value));

or

mapList.forEach((key,value)->{
System.out.println("Key : " + key + " Value : " + value);
});

Login / Signup to Answer the Question.