lotus

贵有恒何必三更眠五更起 最无益只怕一日曝十日寒

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  1846 随笔 :: 0 文章 :: 109 评论 :: 288万 阅读

特性

jdk8中使用了::的用法。就是把方法当做参数传到stream内部,使stream的每个元素都传入到该方法里面执行一下,双冒号运算就是Java中的[方法引用],[方法引用]的格式是:

  类名::方法名 

注意此处没有()。

案例:

表达式:

person -> person.getAge();

使用双冒号:

Person::getAge

表达式:

new HashMap<>()

使用双冒号:

HsahMap :: new

部分代码案例

未使用双冒号

public class MyTest {
    public static void main(String[] args) {
        List<String> a1 = Arrays.asList("a", "b", "c");

        for (String a : a1) {
            printValur(a);
        };

        a1.forEach(x -> MyTest.printValur(x));


    }

    public static void printValur(String str) {
        System.out.println("print value : " + str);
    }
}

使用后

     a1.forEach(MyTest::printValur);

        Consumer<String> consumer = MyTest::printValur;
        a1.forEach(x -> consumer.accept(x));

未使用双冒号:

     List<String> list = a1.stream().map(x -> x.toUpperCase()).collect(Collectors.toList());
        System.out.println(list.toString());

使用双冒号:


        ArrayList<String> collect = a1.stream().map(String::toUpperCase).collect(Collectors.toCollection(ArrayList::new));
        System.out.println(collect.toString());
 
 
22人点赞
 
技术
 
 


作者:黑客和白帽子的故事
链接:https://www.jianshu.com/p/96b4815d629e
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted on   白露~  阅读(474)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2018-08-09 十年Java架构师分享
点击右上角即可分享
微信分享提示