java 8 Consumer 接口
java 8中开始支持函数式编程,初接触后很不适应,因为和对象的思想相差太多。在某次项目中学习了scala之后再返回来看java 8中的函数,有种似曾相识的感觉。java也在和其他语言的竞争中不断更新自己。先来看源码:
@FunctionalInterface
public interface Consumer<T> {
/**
* 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 Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
只有两个方法,accept() 和 andThen(); consumer接受单值,没有返回值,对传入的值做操作,或者做判断业务。consumer是lambda表达式的类型。
public class ConsumerTest {
@Test
public void testAccept(){
// 判断值
Consumer<Integer> first = x -> {
if(x % 2 == 0){
System.out.println("偶数");
} else {
System.out.println("奇数");
}
};
first.accept(3);
}
@Test
public void testAndThen(){
// andThen操作,先consumer1再执行consumer2,源码中的after参数
Consumer<Integer> consumer1 = x -> System.out.println(x + x);
Consumer<Integer> consumer2 = x -> System.out.println(x * x);
consumer1.andThen(consumer2).accept(3);
}
}
网上介绍的文章很多,上面只是简单的做了一个例子操作。有一个例子还可以的,写在后面