Guava Predicate Predicates

本文通过示例展示了如何使用Guava库中的Predicate进行复杂条件过滤,包括定义多个过滤条件并将其合并,适用于Java集合操作,特别是当Java 8的Predicate不满足需求时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、代码
(1)

package com.example.demo12;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;


public class Test15 {
    public static void main(String[] args) {
        List<User> list=new ArrayList<>();
        User user1=new User("a",17);
        User user2=new User("b",15);
        User user3=new User("c",16);
        list.add(user1);
        list.add(user2);
        list.add(user3);
        Predicate<User> predicate1= user -> {
            if (user.getStudentAge()>16){
                return true;
            }else
                return false;
        };
        Predicate<User> predicate2=user -> {
            if (user.getStudentName()=="a"){
                return true;
            }else
                return false;
        };
        Predicate<User> predicate3 = Predicates.and(predicate1,predicate2);
        List<User> list1=Lists.newArrayList(Iterables.filter(list,predicate3));
        list1.stream().forEach(l->{
            System.out.println(l.toString());
        });
    }
}

(2)

package com.example.demo12;

public class User {
    private String studentName;
    private int studentAge;

    public User() {
    }

    public User(String studentName, int studentAge) {
        this.studentName = studentName;
        this.studentAge = studentAge;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public int getStudentAge() {
        return studentAge;
    }

    public void setStudentAge(int studentAge) {
        this.studentAge = studentAge;
    }

    @Override
    public String toString() {
        return "User{" +
                "studentName='" + studentName + '\'' +
                ", studentAge=" + studentAge +
                '}';
    }
}

2、结果

 User{studentName='a', studentAge=17}

3、解释
(1)此Predicate类不同于Java8的Predicate类,大家引入包的时候不要错了,否则是应用不了Guava的方法的;
(2)我们先准备好一个list,然后定义好list的Predicate条件,这里我们可以定义多个过滤条件,调用Guava的Predicates的and方法(不同于Java8的and方法),可以把多个过滤条件合并起来, 利用Guava的Lists来调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值