先导知识
//函数式接口
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);
}
}
- filter
Stream<T> filter(Predicate<? super T> predicate)
需要一个函数式接口:而item -> item !=null
就是其具体实现。
Predicate
函数接口是判断接口,其内部一个抽象方法boolean test(T t);
,我们只要提供一个实现,这个实现需要一个对象,返回一个boolean值即可,所以可以写成匿名函数item -> item !=null
。
- forEach
forEach(Consumer<? super T> action)
需要一个消费型接口的实现,提供一个对象,无返回值。
System.out::println
就是需要一个对象,无返回值public void println(String x)
。
其他找相应的接口和实现。可能会出现嵌套,封装的情况更复杂而已。原理相同。