个人简单理解:方法的参数可以是函数,这种函数我们一般使用Lambda表达式,但是java是面向对象编程语言,所以对于这样的函数需要给出类型,就有了函数式接口(Functional接口)
定义
函数式接口就是一个具有一个方法的普通接口。像这样的接口,可以被隐式转换为lambda表达式。java.lang.Runnable与java.util.concurrent.Callable是函数式接口最典型的两个例子。在实际使用过程中,函数式接口是容易出错的:如有某个人在接口定义中增加了另一个方法,这时,这个接口就不再是函数式的了,并且编译过程也会失败。为了克服函数式接口的这种脆弱性并且能够明确声明接口作为函数式接口的意图,Java 8增加了一种特殊的注解@FunctionalInterface(Java 8中所有类库的已有接口都添加了@FunctionalInterface注解)
函数输入T返回R
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
消费者
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
生成者
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
预言
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作(aggregate operation),或者大批量数据操作 (bulk data operation)。
Stream.of("a", "aa", "aaa", "aaaa").forEach(x->System.out.println(x));//forEach对每个元素执行consumer
System.out.println("----");
Stream.of("a", "aa", "aaa", "aaaa").filter(x->x.length()>2).forEach(x->System.out.println(x));//filter过滤接收Predicate,返回stream
System.out.println("----");
Stream.of("a", "aa", "aaa", "aaaa").peek(x->System.out.println(x)).map(String::toUpperCase).forEach(x->System.out.println(x));
System.out.println("----");//peek也是遍历执行consumer,不同forEach的是,其结果返回仍然是stream
System.out.println(Stream.of("a", "aa", "aaa", "aaaa").allMatch(x->x.startsWith("a")));//allMactch全部匹配
Stream.of("a", "aa", "aaa", "aaaa").collect(Collectors.toList());//collect收集转换成集合
System.out.println(Stream.of("a", "aa", "aaa", "aaaa").reduce(String::concat).map(String::length).orElse(-1));
public interface Stream<T> extends BaseStream<T, Stream<T>> {
T reduce(T identity, BinaryOperator<T> accumulator);
Optional<T> reduce(BinaryOperator<T> accumulator);
}
reduce 第一个参数是初始值,然后初始值依次与stream中元素做 第二个参数的operator操作,若没有第一个参数返回Optional
Optional
A container object which may or may not contain a non-null value.
If a value is present, {@code isPresent()} will return {@code true} and
{@code get()} will return the value.
Optional.ofNullable("").map(String::length).orElse(-1);