Java8 新特性之 Predicate / Supplier & Consumer

  • Predicate 接收一个参数 返回一个 boolean
  • Supplier 不接收参数 返回一个值
  • Consumer 接收一个参数 不返回值

Predicate

抽象方法

test

1
boolean test(T t);


1
2
3
4
5
boolean test(int a, Predicate<Integer> predicate) {
return predicate.test(a);
}

System.out.println(test(12, a -> a > 13) //false

default 方法

and

1
2
3
Predicate<T> and(Predicate<? super T> other) {
return (t) -> test(t) && other.test(t);
}


1
2
3
4
5
6
7
8
9
10
11
12
boolean test3(int a, Predicate<Integer> predicate1, Predicate<Integer> predicate2) {
return predicate1.and( predicate2 ).test (a);
}

System.out.println (test(12, (a) -> {
System.out.println ("a != 0");
return a == 0;
}, (b) -> {
System.out.println ("haha");
return b >= 12;
} ));
//输出 a != 0 false 第二个表达式被短路

negate

1
2
3
Predicate<T> negate() {
return (t) -> !test(t);
}


1
2
3
4
5
bealoon test2(int a, Predicate<Integer> predicate) {
return predicate.negate ().test (a);
}

System.out.println(test(12, a -> a > 13) //true

or

1
2
3
Predicate<T> or (Predicate<? super T> other) {
return (t) -> test(t) || other.test(t);
}


1
2
3
4
5
6
7
8
9
10
11
12
    boolean test3(int a, Predicate<Integer> predicate1, Predicate<Integer> predicate2) {
return predicate1.or( predicate2 ).test (a);
}

System.out.println (test(12, (a) -> {
System.out.println ("a != 0");
return a != 0;
}, (b) -> {
System.out.println ("haha");
return b >= 12;
} ));
//输出 a != 0 true 第二个表达式被短路

static 方法

isEqual

1
2
3
<T> Predicate<T> isEqual(Object targetRef) {
return (null == tatrgetRef) ? Objects::isNull : object -> targetRef.equals(object);
}

Supplier

抽象方法

get

1
T get();


1
2
3
String getString(Supplier<String> supplier) {
return supplier.get(new String)
}

Consumer

抽象方法

accept

1
void accept(T t);


1
2
3
4
5
void test(String a, Consumer<String> consumer) {
consumer.accept ( a );
}

test ( "hello world", System.out::println);

default 方法

andThen

1
2
3
Consumer<T> andThen(Consumer <? super T> after) {
return (T t) -> { accept(t); after.accept(t);};
}


1
2
3
4
5
6
7
8
9
void test2(String a, Consumer<String> consumer1, Consumer<String> consumer2) {
consumer1.andThen (consumer2 ).accept ( a );
}

test2 ( "hello world", s -> System.out.println (s + " sss"), y -> System.out.println (y + " yyyy") );
/*输出
hello world sss
hello world yyyy
*/

------ end ------