Java API provides foreach() method since jdk1.8v.
This method traverses each element of the collection until all elements have been Processed by the method or an exception is raised.
Exceptions thrown by the Operation are passed to the caller.
foreach() is defined as default method in Iterable interface and overiden in ArrayList and Arrays classes.
(Note: interface allows default and static keywords since jdk1.8v)
Implementation in ArraList:
ArrayList Class implements List interface extends Collection interface extends Iterable interface
foreach() implementation in Iterable:
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
overridden method in ArrayList as below:
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
}
Parameter: This method takes a parameter action which represents the action to be performed for each element.
Returns: This method does not returns anything.
Exception: This method throws NullPointerException if the specified action is null.
In Java 8 using lambda expressions we can simply replace for-each loop with
elements.forEach (e -> System.out.println(e) );
Map in Java does not extends Iterable. Map itself has its own forEach method that you can use to iterate through key-value pairs. Which is not overriden.
This method traverses each element of the collection until all elements have been Processed by the method or an exception is raised.
Exceptions thrown by the Operation are passed to the caller.
foreach() is defined as default method in Iterable interface and overiden in ArrayList and Arrays classes.
(Note: interface allows default and static keywords since jdk1.8v)
Implementation in ArraList:
ArrayList Class implements List interface extends Collection interface extends Iterable interface
foreach() implementation in Iterable:
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
overridden method in ArrayList as below:
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
}
Parameter: This method takes a parameter action which represents the action to be performed for each element.
Returns: This method does not returns anything.
Exception: This method throws NullPointerException if the specified action is null.
In Java 8 using lambda expressions we can simply replace for-each loop with
elements.forEach (e -> System.out.println(e) );
Map in Java does not extends Iterable. Map itself has its own forEach method that you can use to iterate through key-value pairs. Which is not overriden.
0 comments:
Post a Comment