大家是不是经常看到如下代码
List list = Arrays.asList("a","b","c");list.stream().forEach(System.out::println);
![d065496e6597a2ca363ac2f28354a37b.png](https://i-blog.csdnimg.cn/blog_migrate/efa866607d1afa94f5fe2c3480217ad7.jpeg)
这个“::”到底是什么语法呢?
在java 8 中,可以通过 “::” 关键字来访问类的构造方法,对象方法,静态方法。一般有下面几种用法。
访问静态方法 // 使用方法:类名::静态方法名, 如 Integer::parseInt访问对象方法 // 使用方法:实例对象::实例方法,如 String::substring访问构造方法 // 使用方法:类名::new, 如 User::new
下面看几个例子:
List list = Arrays.asList("1","2","3");List collect = list.stream().map(Integer::parseInt).collect(Collectors.toList());List collect = list.stream().map(String::toUpperCase).collect(Collectors.toList());
看到这个大家是不是更好奇了,这个方法String::toUpperCase代表的什么呢?
下面我们单独把String::toUpperCase方法写出来看看
Function function = String::toUpperCase;String hello = function.apply("hello");System.out.println(hello); //HELLO
原来String::toUpperCase返回的是一个函数式接口(函数式接口可以被隐式转换为 lambda 表达式),到这里我们明白了,其实最终调用了function.apply方法。
function源码如下,apply方法就是一个入参和一个出参
@GwtCompatible@FunctionalInterfacepublic interface Function extends java.util.function.Function { @Override @CanIgnoreReturnValue // TODO(kevinb): remove this @Nullable T apply(@Nullable F input); @Override boolean equals(@Nullable Object object);}
因此下面的方法
List collect = list.stream().map(String::toUpperCase).collect(Collectors.toList());
相当于
List collect = list.stream().map(s -> s.toUpperCase()).collect(Collectors.toList());
java 8 还有很多的函数式接口
全部在java.util.function包下
![97a8cbb1abbd902bf70ac9042d3b4192.png](https://i-blog.csdnimg.cn/blog_migrate/c9cf3dc231a01b47e39db39de87e2e4e.jpeg)
我们函数式接口,可以通过lamada表达式更直观的表示,算是java 8 中的一大核心功能。