java8 双冒号::简单探索
java8 出来都一段时间了,但是之前一直都用的基础语法,对lambda用的比较少,最近在看别人的代码的时候,看到双冒号::的写法,虽然看是能看懂,但是自己写的话还是不会,于是就顺手学了一下
首先双冒号::在官方文档里的解释是引用,但是英文渣渣看了半天没看懂,所以找了别的资料,大意是我们搞匿名的时候,接口实现正好可以复用某个已知类的方法,那就把这个类的实现引用过来
看下面demo 应该就能懂了
public class Main23J8 {
public static void main(String[] args) {
final J8maohao j8maohao = new J8maohao();
InterfaceExample a = J8maohao::getm1; //等价InterfaceExample a = (j, s)-> j.getm1(s);
System.out.println(a.get(j8maohao, "s1"));
System.out.println(get1(J8maohao::getm1, j8maohao, "s1"));
System.out.println(get2(J8maohao::getm2, "s2")); //等价 get2((e)-> J8maohao.getm2(e), "s2")
}
private static String get1(InterfaceExample e, J8maohao j8maohao, String s) {
return (String) e.get(j8maohao, s);
}
private static String get2(InterfaceExample2 e, String s) {
return (String) e.get(s);
}
}
class J8maohao {
static String s1 = "s1", s2 = "s2";
static HashMap<String, String> m2 = new HashMap<>();
static {
m2.put(s1, s1);
m2.put(s2, s2);
}
String getm1(String s) {
return m2.get(s);
}
static String getm2(String s) {
return m2.get(s);
}
}
//lambda需要单一方法的接口
interface InterfaceExample<T> {
T get(J8maohao j8maohao, String s);
}
interface InterfaceExample2<T> {
T get(String s);
}