8.2.5 使用Java8新增的Predicate操作集合

8.2.5 使用Java8新增的Predicate操作集合

使用removeIf方法 批量删除 集合中的元素

Java 8Collection集合新增了一个removeIf(Predicate filter)方法:

Collection接口的removeIf方法 描述
default boolean removeIf(Predicate<? super E> filter) Removes all of the elements of this collection that satisfy the given predicate.

该方法将会批量删除符合filter条件的所有元素。

Predicate是函数式接口

该方法需要一个Predicate(谓词)对象作为参数, Predicate也是函数式接口,因此可使用Lambda表达式作为参数。

实例 使用removeIf批量删除集合元素

如下程序示范了使用Predicate来过滤集合。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Collection;
import java.util.HashSet;

public class PredicateTest {
public static void main(String[] args) {
// 创建一个集合
Collection<String> collection = new HashSet<>();
collection.add("1");
collection.add("2");
collection.add("3");
collection.add("4");
collection.add("5");
System.out.println(collection);
System.out.println("------------------------");
// removeIf方法使用Lambda表达式删除满足Lambda表达式的集合元素
collection.removeIf(str -> Integer.valueOf(str) > 3);
System.out.println(collection);
}
}
1
2
3
[1, 2, 3, 4, 5]
------------------------
[1, 2, 3]

上面程序中调用了Collection集合的removeIf()方法批量删除集合中符合条件的元素,程序传入一个Lambda表达式作为过滤条件

函数式接口Predicate的抽象方法 test

Predicate的抽象方法 描述
boolean test(T t) Evaluates this predicate on the given argument.

Predicatetest方法可以判断一个对象是否满足谓词中给定的条件.

使用Predicate类的test方法统计集合元素

可以创建一个countCollectionByPredicate方法,第一个参数是Collection,第二个参数是Predicate,
然后就可以在方法中遍历集合元素时,计算Predicate对象.test(集合元素)方法返回true的次数,从而实现对集合元素的统计.

实例Predicate统计集合元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.*;
import java.util.function.*;

public class PredicateTest2 {
public static void main(String[] args) {
// 创建books集合、为books集合添加元素的代码与前一个程序相同。
Collection<String> collection = new HashSet<>();
collection.add("HelloWorld");
collection.add("C");
collection.add("C++");
collection.add("Java");
collection.add("JavaScirpt");
System.out.println(collection);
System.out.println("----------------------------");
System.out.println("包含字符C的语言个数:" + countCollectionByPredicate(collection, str -> str.contains("C")));
System.out.println("以字符J开头的语言个数:" + countCollectionByPredicate(collection, str -> str.startsWith("J")));
System.out.println("大写字母开头的语言个数:"
+ countCollectionByPredicate(collection, str -> str.charAt(0) <= 'Z' && str.charAt(0) >= 'A'));
}

/**
* 统计集合中符合给定谓词的元素的个数.
*
* @param collection 要统计的集合.
* @param predicate 谓词.
* @return 集合中满足给定谓词的元素的个数.
*/
public static int countCollectionByPredicate(Collection<String> collection, Predicate<String> predicate) {
int total = 0;
for (String str : collection) {
// 使用Predicate的test()方法判断该对象是否满足Predicate指定的条件
if (predicate.test(str)) {
total++;
}
}
return total;
}
}

运行效果如下:

1
2
3
4
5
[Java, C++, C, JavaScirpt, HelloWorld]
----------------------------
包含字符C的语言个数:2
以字符J开头的语言个数:2
大写字母开头的语言个数:5