Predicate
这个接口可以用于做一些过滤操作,它的源码如下:
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
他要求传入一个数据类型返回bool类型的结果
下面是我对它的测试
public static void main(String[] args) {
Book book =new Book();
book.setNumber(100);
boolean result = testPredic(e -> e.getNumber() > 10,book);
System.out.println(result);
}
public static boolean testPredic(Predicate<Book> bookPredicate, Book book) {
return bookPredicate.test(book);
}
结果:true
我输入一个条件
e->e.getNumber()>10
一个对象book然后对book的属性进行判断得到一个bool的结果。
他有and,or,negat等多个方法,这些方法也都非常简单,分别 表示&&,||,^取反,下面是个简单的例子。
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
List<Integer> list = new ArrayList<>();
for (int i : numbers) {
list.add(i);
}
Predicate<Integer> p1 = i -> i > 5;
System.out.println("Pricicate :" + p1.test(6));
Predicate<Integer> p2 = i -> i < 20;
Predicate<Integer> p3 = i -> i % 2 == 0;
//小于20并且是偶数
List test = list.stream().filter(p1.and(p2).and(p3)).collect(Collectors.toList());
System.out.println(test.toString());
}
我们再实际传参的时候可以进行灵活的条件判断。
Supplier
看下面一段代码
public static void main(String[] args) {
testSupplier(() -> Book.builder().id(12).name("hello").number(23).build());
}
public static <T> void testSupplier(Supplier<T> supplier) {
T t = supplier.get();
System.out.println(t);
}
它的源码很简单:
直接给一个值,然后这个值我们就可以用了,通过调用get方法获取这个值,给人的感觉就是将这个对象包装了一层,需要的时候直接获取。在我们的项目 中的使用:
实际调用:
Consumer
源码如下:
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
顾名思义,消费型,我们创建一个操作,需要执行并且不需要返回值使用这个Consumer
测试demo如下:
@Test
public void cutHand() {
Goods goods = new Goods("口红", 288);
spentMoney(goods, (g) -> System.out.println("消费" + g.getCost() + "元"));
System.out.println("-------------------贫富分割线--------------------");
spentMoneyAndLog(goods, (g) -> System.out.println("消费" + g.getCost() + "元"));
}
public void spentMoney(Goods goods, Consumer<Goods> consumer) {
consumer.accept(goods);
}
public void spentMoneyAndLog(Goods goods, Consumer<Goods> consumer) {
Consumer<Goods> logConsumer = (g) -> System.out.println("买" + g.getGoodsName() + "用了" + g.getCost() + "元!");
consumer.andThen(logConsumer).accept(goods);
}
这个cousumer有点类似Function的工作模式,提供了andThen方法,一个消费完了,另外一个还可以继续处理。