openJDK的版本是openJDK8,如何下載openJDK,請參考個人這篇博客。java
這篇內容很簡單。less
List-1 List的forEach例子ui
@Test public void test1() { List<Integer> integers = Arrays.asList(1, 4, 7, 9, 20, 3, 5, -1, -7, 10); integers.forEach(i->{ System.out.println(i); }); }
Arrays.asList中底層上是ArrayList,forEach的實現是在接口java.lang.Iterable中,以下List-2所示,JDK8中interface是能夠有實現方法的(JDK的特性),因爲該方法在Iterable中,因此直接用迭代的方式遍歷整個List,以後對每一個元素,調用Consumer.accept(T)方法。this
List-2 Iterable的forEach方法spa
/** * Performs the given action for each element of the {@code Iterable} * until all elements have been processed or the action throws an * exception. Unless otherwise specified by the implementing class, * actions are performed in the order of iteration (if an iteration order * is specified). Exceptions thrown by the action are relayed to the * caller. * * @implSpec * <p>The default implementation behaves as if: * <pre>{@code * for (T t : this) * action.accept(t); * }</pre> * * @param action The action to be performed for each element * @throws NullPointerException if the specified action is null * @since 1.8 */ default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } }
看下面的圖1,List接口繼承了Iterable接口:.net
圖1 List的類繼承圖code