Lambda表达式,函数式编程,方法引用

先导知识

//函数式接口
public interface TestClassInterFace {
    public void call();
}


class TestCallImpl{
    public static void callImpl(){
        System.out.println("实现成功");
    }

	/**
	TestClassInterFace 中只有一个 call() 抽象方法,无参
	TestCallImpl 提供一个相应的无参方法来做实现
	只要所需参数列表对应,就可以直接对接口进行实现,节省了创建实现类的过程。与方法名无关。
	*/
    public static void main(String args[]) {
        TestClassInterFace interFace = TestCallImpl::callImpl;
        TestClassInterFace interFace2 = () -> {System.out.println("实现成功");};
        interFace.call(); //实现成功
        interFace2.call(); //实现成功 
    }
}

看一下相关的介绍文章

https://www.cnblogs.com/aiqiqi/p/11004208.html

java8提供了一系列常见的函数式接口,最常用的如下几个:

  • Function:提供任意一种类型的参数,返回另外一个任意类型返回值。 R apply(T t);

  • Consumer:提供任意一种类型的参数,返回空值。 void accept(T t);

  • Supplier:参数为空,得到任意一种类型的返回值。T get();

  • Predicate:提供任意一种类型的参数,返回boolean返回值。boolean test(T t);

Stream流实战

public class CalcLong {
    public static void main(String[] args) {

        List<String>strings = Arrays.asList("abc", null, "bc", "efg", "abcd",null, "jkl");
        List<String> filtered = strings.stream().filter(item -> item !=null).collect(Collectors.toList());
        filtered.forEach(System.out::println);
        
    }

}
  1. filter
    Stream<T> filter(Predicate<? super T> predicate) 需要一个函数式接口:而 item -> item !=null 就是其具体实现。

Predicate 函数接口是判断接口,其内部一个抽象方法boolean test(T t); ,我们只要提供一个实现,这个实现需要一个对象,返回一个boolean值即可,所以可以写成匿名函数item -> item !=null

  1. forEach
    forEach(Consumer<? super T> action) 需要一个消费型接口的实现,提供一个对象,无返回值。
    System.out::println 就是需要一个对象,无返回值 public void println(String x)

其他找相应的接口和实现。可能会出现嵌套,封装的情况更复杂而已。原理相同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值