predicate<T> 接口 的使用方法

predicate<T> 接口 的使用

简介

predicate 是Java 8 提供的一个定义判断条件的接口;因为Java 8支持lambda,所以用lambda写简便点

Java 7之前的写法

import java.util.function.Predicate;

public class Main {
    public static void main(){
        // 这种定义方式很影响阅读代码
        Predicate<String> condition = new Predicate<String>() {
			    @Override
			    public boolean test(String s) {
        		return s.isEmpty();
    		}
		};
    }
}

java 8之后的写法(lambda)

Predicate<String> condition1 = s -> s.isEmpty();

使用

用于字符串过滤

Predicate<String> condition1 = s -> s.length() > 3 ;//第一个条件,字符串长度大于3
Predicate<String> condition2 = s -> s.length() < 5;//第二个条件,字符串长度小于5

List<String> list = Arrays.asList("jack","tom","tommy","bob","alice");
Stream<String> strings = list.stream().filter(condition1);//用第1个条件做过滤
strings.forEach(System.out::println);
strings = list.stream().filter(condition2);//用第2个条件做过滤
strings.forEach(System.out::println);

and 多个条件与

Predicate<String> condition1 = s -> s.length() > 3 ;//第一个条件,字符串长度大于3
Predicate<String> condition2 = s -> s.length() < 5;//第二个条件,字符串长度小于5

List<String> list = Arrays.asList("jack","tom","tommy","bob","alice");
Stream<String> strings = list.stream().filter(condition1.and(condition2));//用第1个条件和第2个条件做“与运算”对字符串过滤
strings.forEach(System.out::println);

or 多条件或

Predicate<String> condition1 = s -> s.length() < 4; //第一个条件,字符串长度大于3
Predicate<String> condition2 = s -> s.length() >= 5;//第二个条件,字符串长度小于5

List<String> list = Arrays.asList("jack","tom","tommy","bob","alice");
Stream<String> strings = list.stream().filter(condition1.or(condition2));//用第1个条件和第2个条件做“或运算”对字符串过滤
strings.forEach(System.out::println);

negate 逻辑非

Predicate<String> condition1 = s -> s.length() < 4; //第一个条件,字符串长度大于3
List<String> list = Arrays.asList("jack","tom","tommy","bob","alice");
Stream<String> strings = list.stream().filter(condition1.negate());//过滤长度不小于4的名字

拓展一下

Predicate.isEqual(Object)方法

首先判断对象是否是null,最后再做equal比较

Predicate<String> condition = s -> Predicate.isEqual("jack").test(s);
List<String> list = Arrays.asList("jack","tom","tommy","bob","alice");
Stream<String> strings = list.stream().filter(condition);// 仅将Jack过滤出来
strings.forEach(System.out::println);
posted @ 2023-11-23 22:07  勤匠  阅读(115)  评论(0编辑  收藏  举报