java.util.function 包

java.util.function 包

1. Function

接收一个参数,并返回一个结果

2. BiFunction

接收两个参数,并返回一个结果

3. BinaryOperator

二元操作符,根据两个参数来返回一个计算结果。继承 BiFunction,具体写法上会更加简单,

1
2
BinaryOperator<Integer> func = (n1, n2) -> n1 + n2;
func.apply(1, 2);

apply 就相当于是一个传参的过程,具体返回结果需要看 func 具体实现过程。

默认函数里实现了 minBy / maxBy 两种,可以自己实现 Comparator 然后传到方法中。

1
2
3
4
public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator);
return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
}

4. Predicate

对某种类型的数据进行判断,从而得到一个boolean值结果

4.1 test

Predicate 接口中包含一个抽象方法: boolean test(T t)

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.function.Predicate;

public class Demo01Predicate {
public static void main(String[] args) {
method(s -> s.length() > 5);
}

private static void method(Predicate<String> predicate) {
boolean veryLong = predicate.test("HelloWorld");
System.out.println("字符串很长吗:" + veryLong); // 字符串很长吗:true
}
}

条件判断的标准是传入的Lambda表达式逻辑

4.2 and 与

1
2
3
4
5
源码:
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.function.Predicate;

public class DemoPredicateAnd {
public static void main(String[] args) {
boolean isValid = method(
// String.contains()方法,仅当此字符串包含指定的字符值序列时返回true。
s -> s.contains("H"),
s -> s.contains("W")
);
System.out.println("字符串符合要求吗:" + isValid); // 字符串符合要求吗:false
}

private static boolean method(Predicate<String> one, Predicate<String> two) {
boolean isValid = one.and(two).test("Hello world");
return isValid;
}
}

4.3 or 或

1
2
3
4
5
源码:
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}

4.4 negate 取反

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