本篇文章小编给大家分享一下Java8 Supplier接口和Consumer接口原理代码解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
Supplier接口
package java.util.function;
/**
* Represents a supplier of results.
*
*
There is no requirement that a new or distinct result be returned each
* time the supplier is invoked.
*
*
This is a functional interface
* whose functional method is {@link #get()}.
*
* @param the type of results supplied by this supplier
*
* @since 1.8
*/
@FunctionalInterface
public interface Supplier{
/**
* Gets a result.
*
* @return a result
*/
T get();
}
supplier接口只有一个抽象方法get(),通过get方法产生一个T类型实例。
实例:
package me.yanand;
import java.util.function.Supplier;
public class TestSupplier {
public static void main(String[] args) {
SupplierappleSupplier = Apple::new;
System.out.println("--------");
appleSupplier.get();
}
}
class Apple{
public Apple() {
System.out.println("创建实例");
}
}
Consumer接口
package java.util.function;
import java.util.Objects;
/**
* Represents an operation that accepts a single input argument and returns no
* result. Unlike most other functional interfaces, {@code Consumer} is expected
* to operate via side-effects.
*
*
This is a functional interface
* whose functional method is {@link #accept(Object)}.
*
* @param the type of the input to the operation
*
* @since 1.8
*/
@FunctionalInterface
public interface Consumer{
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
/**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default ConsumerandThen(Consumer super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
实例:
package me.yanand;
import java.util.function.Consumer;
public class TestConsumer {
public static void main(String[] args) {
Consumerconsumer = (t) -> {
System.out.println(t*3);
};
ConsumerconsumerAfter = (s) -> {
System.out.println("之后执行:"+s);
};
consumer.andThen(consumerAfter).accept(5);
}
}