前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >openJDK之lambda——List的forEach如何实现的

openJDK之lambda——List的forEach如何实现的

作者头像
克虏伯
发布2019-04-15 10:35:13
6570
发布2019-04-15 10:35:13
举报

    openJDK的版本是openJDK8,如何下载openJDK,请参考我的这篇博客

    这篇内容很简单。

1.List的forEach如何实现

List-1 List的forEach例子

代码语言:javascript
复制
@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)方法。

List-2 Iterable的forEach方法

代码语言:javascript
复制
/**
    * 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接口:

                                                              图1 List的类继承图

代码语言:txt
复制
 (adsbygoogle = window.adsbygoogle || []).push({});
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018/09/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.List的forEach如何实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档