Consumer篇
1 import com.alibaba.fastjson.JSON; 2 import java.util.ArrayList; 3 import java.util.List; 4 import java.util.function.Consumer; 5 import java.util.stream.Stream; 6 7 public class UserConsumer { 8 9 public static void main(String[] args) { 10 11 /** 12 * Consumer的作用顾名思义: 13 * 给定义一个参数,对其进行(消费)处理,处理的方式可以是任意操作 14 * 15 * 其核心方法如下: 16 * void accept(T t); 对给定的参数T执行定义的操作 17 * default Consumer<T> andThen(Consumer<? super T> after) 对给定的参数T执行定义的操作执行再继续执行after定义的操作 18 * 19 * 与Consumer<T>相关的接口: 20 * BiConsumer<T, U> 处理一个两个参数 21 * DoubleConsumer 处理一个double类型的参数 22 * IntConsumer 处理一个int类型的参数 23 * LongConsumer 处理一个long类型的参数 24 * ObjIntConsumer<T> 处理两个两个参数,且第二个参数必须为int类型 25 * ObjLongConsumer<T> 处理两个两个参数,且第二个参数必须为long类型 26 */ 27 28 // accept(T t) 比如将给定的一批用户里面的名称为"lisi"的用户都给打包起来 29 List<Person> lisiList = new ArrayList<>(); 30 Consumer<Person> consumer = x -> { 31 if (x.getName().equals("lisi")) { 32 lisiList.add(x); 33 } 34 }; 35 Stream.of( 36 new Person(21, "zhangsan"), 37 new Person(22, "lisi"), 38 new Person(23, "wangwu"), 39 new Person(24, "wangwu"), 40 new Person(23, "lisi"), 41 new Person(26, "lisi"), 42 new Person(26, "zhangsan") 43 ).forEach(consumer); 44 System.out.println(JSON.toJSONString(lisiList)); 45 46 47 // andThen(Consumer<? super T> after) 比如将给定的一批用户里面的名称为"lisi"且年龄大于22岁的用户都给打包起来 48 List<Person> lisiList = new ArrayList<>(); 49 Consumer<Person> consumer = x -> { 50 if (x.getName().equals("lisi")) { 51 lisiList.add(x); 52 } 53 }; 54 consumer = consumer.andThen(x -> lisiList.removeIf(y -> y.getAge() < 23)); 55 Stream.of( 56 new Person(21, "zhangsan"), 57 new Person(22, "lisi"), 58 new Person(23, "wangwu"), 59 new Person(24, "wangwu"), 60 new Person(23, "lisi"), 61 new Person(26, "lisi"), 62 new Person(26, "zhangsan") 63 ).forEach(consumer); 64 System.out.println(JSON.toJSONString(lisiList)); 65 } 66 }