jdk8-Consumer接口

Consumer的作用是给定义一个参数,对其进行(消费)处理,处理的方式可以是任意操作.
源代码如下:
Consumer<T> void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after);

andThen方法返回一个Consumer,以便于链式操作,值得注意的是,andThen方法是建立在accept基础之上的。执行的顺序是先执行accept,再执行andThen操作。

accept示例:
Consumer<Person> consumer = (p) -> System.out.println(p.getFirstName());//定义消费行为
consumer.accept(Person.builder().firstName("zs").build());//执行消费行为
andThen示例:
 Consumer<Person> consumer = (p) -> System.out.println(p.getFirstName());
 consumer.andThen((p) -> System.out.println(p.getLastName())).accept(Person.builder().firstName("san feng").lastName("zhang").build());

 Consumer有相关的原始类型实现,是Consumer的特例(This is the primitive type specialization of{@link Consumer} for {@code double}.)

 相关的实现有三个IntConsumer,LongConsumer,DoubleConsumer.

accept示例:
 DoubleConsumer doubleConsumer = (d) -> System.out.println(d);
 doubleConsumer.accept(23.2d);

BiConsumer是对两个参数进行消费.

accept示例:

  BiConsumer<String, Person> biConsumer = (str, p) -> System.out.println(str + p.getFirstName());
  biConsumer.accept("hello ", Person.builder().firstName("san feng").lastName("zhang").build());

BiConsumer的原始类型实现也有三个,ObjIntConsumer,ObjLongConsumer,ObjDoubleConsumer

accept示例:

 
ObjIntConsumer<Person> objIntConsumer = (Person ps, int i) -> {
ps.setAge(i);
System.out.println(ps.getFirstName()+":"+ps.getAge());
};
objIntConsumer.accept(Person.builder().firstName("san feng").lastName("zhang").build(), 300);
Consumer相关的函数式接口,只有这8个。按参数个数分为两种,每种又有三个原始类型的特殊实现,使用原始类型的相关实现,效率会高一点。

猜你喜欢

转载自www.cnblogs.com/lastsoul/p/10268324.html