Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the point of having both Iterator.forEachRemaining() and Iterable.forEach()?

and both of them get a Consumer as parameter. so if Java 8, is meant to avoid confusions, like it has done in Time API, why has it added a new confusion? or am I missing some point?

like image 207
mostafa.S Avatar asked Feb 26 '17 07:02

mostafa.S


People also ask

What is the difference between forEach and forEachRemaining in Java?

forEach iterates through the elements of an Iterable . forEachRemaining iterates through the remaining elements of an Iterator .

What does the forEach () method on Iterable do?

The forEach() method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

What is the difference between iterator and forEach?

Difference between the two traversals In for-each loop, we can't modify collection, it will throw a ConcurrentModificationException on the other hand with iterator we can modify collection. Modifying a collection simply means removing an element or changing content of an item stored in the collection.

What is difference between iterator and Iterable in Java?

Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.


1 Answers

To understand why the two methods both exist, you need to first understand what are Iterator and Iterable.

An Iterator basically is something that has a "next element" and usually, an end.

An Iterable is something that contains elements in a finite or infinite sequence and hence, can be iterated over by keep getting the next element. In other words, Iterables can be iterated over by Iterators.

Now that you understand this, I can talk about what's the difference between the two methods in question.

Let's use an array list as an example. This is what is inside the array list:

[1, 3, 6, 8, 0] 

Now if I call Iterable.forEach() and pass in System.out::print(), 13680 will be printed. This is because Iterable.forEach iterates through the whole sequence of elements.

On the other hand, if I get the Iterator of the array list and called next twice, before calling forEachRemaining with System.out::print(), 680 will be printed. The Iterator has already iterated through the first two elements, so the "remaining" ones are 6, 8 and 0.

like image 72
Sweeper Avatar answered Oct 05 '22 23:10

Sweeper