本文使用简单的例子来说明 Predicate 的用法。
本文示例使用 Stream Api :
1 Stream<T> filter (Predicate<? super T> predicate) ;
使用 Predicate 来过滤 list : 例如我们有个数据 List 如下:
1 List<String> names = Arrays.asList("Jack" , "Tom" , "James" , "Dwight Howard" );
单条件过滤: 1 2 3 4 5 6 7 private static void listFilter (List<String> names) { List<String> result = names.stream() .filter(name -> name.startsWith("J" )) .collect(Collectors.toList()); System.out.println("listFilter startsWith J :" + result); }
多条件过滤: 1 2 3 4 5 6 7 8 private static void listMultiFilter (List<String> names) { List<String> result = names.stream() .filter(name -> name.startsWith("J" )) .filter(name -> name.contains("c" )) .collect(Collectors.toList()); System.out.println("listMultiFilter 1 startsWith J and contains c :" + result); }
等同于
1 2 3 4 List<String> result = names.stream() .filter(name -> name.startsWith("J" ) && name.contains("c" )) .collect(Collectors.toList());
组合使用 Predicate:Predicate.and() 两个条件都需要满足 1 2 3 4 5 6 7 8 private static void listFilterPredicateAnd (List<String> names) { Predicate<String> predicate1 = str -> str.contains("a" ); Predicate<String> predicate2 = str -> str.length() > 5 ; List<String> result = names.stream() .filter(predicate1.and(predicate2)) .collect(Collectors.toList()); System.out.println("listFilterPredicateAnd contains a and length > 5 :" + result); }
Predicate.or() 两个条件满足其中一个 1 2 3 4 5 6 7 8 private static void listFilterPredicateOr(List<String> names) { Predicate<String> predicate1 = str -> str.contains("a" ); Predicate<String> predicate2 = str -> str.length() > 5; List<String> result = names.stream() .filter(predicate1.or(predicate2)) .collect(Collectors.toList()); System.out.println("listFilterPredicateOr contains a or length > 5 :" + result); }
Predicate.negate() 对条件取反 1 2 3 4 5 6 7 private static void listFilterPredicateNegate (List<String> names) { Predicate<String> predicate1 = str -> str.contains("a" ); List<String> result = names.stream() .filter(predicate1.negate()) .collect(Collectors.toList()); System.out.println("listFilterPredicateNegate Does not contains a :" + result); }
用 main 方法分别执行以上方法 1 2 3 4 5 6 7 8 public static void main (String[] args) { List<String> names = Arrays.asList("Jack" , "Tom" , "James" , "Dwight Howard" ); listFilter(names); listMultiFilter(names); listFilterPredicateAnd(names); listFilterPredicateOr(names); listFilterPredicateNegate(names); }
输出结果为:
1 2 3 4 5 6 listFilter startsWith J :[Jack, James] listMultiFilter 1 startsWith J and contains c :[Jack] listMultiFilter 2 startsWith J and contains c :[Jack] listFilterPredicateAnd contains a and length > 5 :[Dwight Howard] listFilterPredicateOr contains a or length > 5 :[Jack, James, Dwight Howard] listFilterPredicateNegate Does not contains a :[Tom]
本文代码完整示例地址: Github