2020-09-07

java8 :: 用法 (JDK8 双冒号用法)

特性

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

  类名::方法名

注意此处没有()。

案例:

表达式:

person->person.getAge();

使用双冒号:

Person::getAge

表达式:

newHashMap<>()

使用双冒号:

HsahMap ::new

部分代码案例

未使用双冒号

publicclassMyTest{publicstaticvoidmain(String[] args) {        List a1= Arrays.asList("a","b","c");for(String a: a1){printValur(a);};        a1.forEach(x-> MyTest.printValur(x));}publicstaticvoidprintValur(String str) {        System.out.println("print value : "+ str);}}

使用后

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

未使用双冒号:

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

使用双冒号:

ArrayList collect= a1.stream().map(String::toUpperCase).collect(Collectors.toCollection(ArrayList::new));        System.out.println(collect.toString());

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。