Lambda 表达式之从 foreach(out::println) 到自定义输出

一、引言

List<String> str1 = new ArrayList<>();
str1.add("hello");
str1.add("world");
//下面就是lambda表达式之“::”的应用了
str1.forEach(System.out::println);
//两种方式等效
str1.forEach((item)->{
    
    
	System.out.println(item);
});

这个双冒号的原理,就是将左边的System.out类,联合foreach原本的参数作为输入,然后将参数装配进out类的println(String x)函数(使用foreach原本的参数作为println(String x)参数);

二、所以该冒号总共有三种使用方式:

  1. 类::静态方法
  2. 实例::方法
  3. 类::实例方法

对应来说:

1.::静态方法
--工具类的方法经常被用来使用,该方法是static的
Utils::generateRandom;
Utils.generateRandom(); //等于这种写法

2.实例::方法
Animal cat = new Cat();
cat::eat;  //前面是实例对象,后面的方法可以不是static
new Cat()::eat; //当然也可以这样写
--按Ctrl+Alt+V,可推出前面[idea],可以看到返回的是一个 @FunctionalInterface 功能性接口
--因为我写的返回值是void所以是Runnable,可以自行试试其他的
Runnable speak = new Test3()::speak;

3.::实例方法
--上面我们知道返回的其实是定义的功能性接口,那么接下来这种,我们就自己定义一个接口
--通常我们这样写,主要是因为我们准备用的方法不是静态类型的,在不改变他们的情况下,
--我们可以自己定义一个接口,来使用这个方法;
public class Test1 {
    
    
    public void a(Integer param1,int param2){
    
    
    }
    public static void main(String[] args) {
    
    
        --可以传入[定义的类][Test2]或者[定义的类的父类][Test1]传入进去,向上兼容,向方法少的兼容;
        MyInter m = Test1::a;
        
        MyInter myInter = (test2, p1, p2) -> test2.speak(p1, p2);//默认是Test2
    }
}
class Test2 extends Test1 {
    
    
    void speak(Integer param1,int param2){
    
    

    }
}
@FunctionalInterface
interface MyInter {
    
    
    --接口参数比上述的a方法参数数量多一个,即被调用的类[第一个],其它参数要一致
    --且Test1::a的Test1是该入参类型Test2的父类,向少的类扩展
    public void d(Test2 d,int param1,int param2);
}

以上,就是关于"::"的使用方法;
现在,你知道如何自己定义一个输出了吗?


附:(自定义输出)

public static void main(String[] args) {
    
    
	List<String> list = new ArrayList<>();
	list.add("hello");
	list.add("world");
	list.forEach(this::addSomething);
}
void addSomething(String s){
    
    
	System.out.println(s+" Doge!");
}
// map遍历
map.entrySet().forEach(entry -> 
				System.out.println(entry.getKey() + entry.getValue()));
---
map.entrySet().iterator().forEachRemaining(item ->
				System.out.println(item.getKey()+item.getValue()));
---
map.forEach( (k, v) -> {
    
    
				System.out.println("key:value = " + k + ":" + v);
				});

转载请加上本文链接:https://blog.csdn.net/howeres/article/details/108040741

猜你喜欢

转载自blog.csdn.net/howeres/article/details/108040741