12.3 常用函数式接口

12.3.5 Predicate接口

  有时候需要对某种类型的数据进行判断,以得到一个boolean值结果。这时可以使用java.util.function.Predicate<T> 接口。

抽象方法:test

  Predicate 接口中包含一个抽象方法:boolean test(T t)。用于条件判断的场景:

1
2
3
4
5
6
7
8
9
10
import java.util.function.Predicate;
public class Demo15PredicateTest {
private static void method(Predicate<String> predicate) {
boolean veryLong = predicate.test("HelloWorld");
System.out.println("字符串很长吗:" + veryLong);
}
public static void main(String[] args) {
method(s ‐> s.length() > 5);
}
}

  条件判断的标准是传入的Lambda表达式逻辑,只要字符串长度大于5则认为很长。

默认方法:

  and既然是条件判断,就会存在与、或、非三种常见的逻辑关系。其中将两个Predicate 条件使用“与”逻辑连接起来实现“并且”的效果时,可以使用default方法and 。其JDK源码为:

1
2
3
4
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) ‐> test(t) && other.test(t);
}

  如果要判断一个字符串既要包含大写“H”,又要包含大写“W”,那么:

1
2
3
4
5
6
7
8
9
10
11
import java.util.function.Predicate;
public class Demo16PredicateAnd {
private static void method(Predicate<String> one,
Predicate<String> two) {
boolean isValid = one.and(two).test("Helloworld");
System.out.println("字符串符合要求吗:" + isValid);
}
public static void main(String[] args) {
method(s ‐> s.contains("H"), s ‐> s.contains("W"));
}
}

默认方法:or

  与and的“与”类似,默认方法or实现逻辑关系中的“或”。JDK源码为:

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

  如果希望实现逻辑“字符串包含大写H或者包含大写W”,那么代码只需要将“and”修改为“or”名称即可,其他都不变:

1
2
3
4
5
6
7
8
9
10
11
import java.util.function.Predicate;
public class Demo16PredicateAnd {
private static void method(Predicate<String> one,
Predicate<String> two) {
boolean isValid = one.or(two).test("Helloworld");
System.out.println("字符串符合要求吗:" + isValid);
}
public static void main(String[] args) {
method(s ‐> s.contains("H"), s ‐> s.contains("W"));
}
}

默认方法:negate

  “与”、“或”已经了解了,剩下的“非”(取反)也会简单。默认方法negate 的JDK源代码为:

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

  从实现中很容易看出,它是执行了test方法之后,对结果boolean值进行“!”取反而已。一定要在test 方法调用之前调用negate 方法,正如andor 方法一样:

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

public class Demo17PredicateNegate {
private static void method(Predicate<String> predicate) {
boolean veryLong = predicate.negate().test("HelloWorld");
System.out.println("字符串很长吗:" + veryLong);
}
public static void main(String[] args) {
method(s ‐> s.length() < 5);
}
}

12.3.6 练习:集合信息筛选

题目

  数组当中有多条“姓名+性别”的信息如下,请通过Predicate 接口的拼装将符合要求的字符串筛选到集合ArrayList 中,需要同时满足两个条件:

  1. 必须为女生;

  2. 姓名为4个字。

    1
    2
    3
    4
    5
    6
    public class DemoPredicate {
    public static void main(String[] args) {
    String[] array = { "迪丽热巴,女", "古力娜扎,女",
    "马尔扎哈,男", "赵丽颖,女" };
    }
    }

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class DemoPredicate {
public static void main(String[] args) {
String[] array = { "迪丽热巴,女", "古力娜扎,女",
"马尔扎哈,男", "赵丽颖,女" };
List<String> list = filter(array,
s ‐> "女".equals(s.split(",")[1]),
s ‐> s.split(",")[0].length() == 4);
System.out.println(list);
}
private static List<String> filter(String[] array,
Predicate<String> one,Predicate<String> two) {
List<String> list = new ArrayList<>();
for (String info : array) {
if (one.and(two).test(info)) {
list.add(info);
}
}
return list;
}
}

12.3.7 Function接口

  java.util.function.Function<T,R>接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件,后者称为后置条件。

抽象方法:apply

  Function接口中最主要的抽象方法为:R apply(T t) ,根据类型T的参数获取类型R的结果。

使用的场景例如:将String类型转换为Integer类型。

1
2
3
4
5
6
7
8
9
10
import java.util.function.Function;
public class Demo11FunctionApply {
private static void method(Function<String, Integer> function) {
int num = function.apply("10");
System.out.println(num + 20);
}
public static void main(String[] args) {
method(s ‐> Integer.parseInt(s));
}
}

当然,最好是通过方法引用的写法。

默认方法:andThen

  Function接口中有一个默认的andThen 方法,用来进行组合操作。JDK源代码如:

1
2
3
4
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) ‐> after.apply(apply(t));
}

  该方法同样用于“先做什么,再做什么”的场景,和Consumer中的andThen差不多:

1
2
3
4
5
6
7
8
9
10
11
import java.util.function.Function;
public class Demo12FunctionAndThen {
private static void method(Function<String, Integer> one,
Function<Integer, Integer> two) {
int num = one.andThen(two).apply("10");
System.out.println(num + 20);
}
public static void main(String[] args) {
method(str‐>Integer.parseInt(str)+10, i ‐> i *= 10);
}
}

  第一个操作是将字符串解析成为int数字,第二个操作是乘以10。两个操作通过andThen 按照前后顺序组合到了一起。

请注意,Function的前置条件泛型和后置条件泛型可以相同。

12.3.8 练习:自定义函数模型拼接

题目

  请使用Function 进行函数模型的拼接,按照顺序需要执行的多个函数操作为:

String str = “赵丽颖,20”;

  1. 将字符串截取数字年龄部分,得到字符串;
  2. 将上一步的字符串转换成为int类型的数字;
  3. 将上一步的int数字累加100,得到结果int数字。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.function.Function;
public class DemoFunction {
public static void main(String[] args) {
String str = "赵丽颖,20";
int age = getAgeNum(str, s ‐> s.split(",")[1],
s ‐>Integer.parseInt(s), n ‐> n += 100);
System.out.println(age);
}
private static int getAgeNum(String str, Function<String, String> one,
Function<String, Integer> two,
Function<Integer, Integer> three) {
return one.andThen(two).andThen(three).apply(str);
}
}