# 1. 简介

Predicate<泛型>（断言，断定），是Guava中的一个基础接口，其内部只有一个方法`boolean apply(T input)`，这个方法输入是一个泛型对象，输出是一个布尔值，非常简单，下面来看一下这个小东西能帮助我们做什么。

# 2. 使用

## 2.1 更简单的过滤

```List<Integer> intList = Lists.newArrayList(1, 2, 3, 5, 6);
Iterator<Integer> it = intList.iterator();
while (it.hasNext()) {
Integer value = it.next();
if (value == 3 || value == 5) {
it.remove();
}
}
System.out.println(intList);```

```List<Integer> intList = Lists.newArrayList(1, 2, 3, 5, 6);
List<Integer> resultList = Lists.newArrayList();
for (Integer value : intList) {
if (value != 3 && value != 5) {
resultList.add(value);
}
}
System.out.println(resultList);```

```List<Integer> intList = Lists.newArrayList(1, 2, 3, 5, 6);
Predicate<Integer> predicate = new Predicate<Integer>() {
public boolean apply(Integer value) {
return value != 3 && value != 5;
}
};
List<Integer> resultList = Lists.newArrayList(Iterables.filter(intList, predicate));
System.out.println(resultList);```

## 2.2 更优雅的判断

```private boolean canExam(Examinee examinee) {
return ("大专".equals(examinee.getEducation()) && examinee.getExperience() >= 5)
|| ("本科".equals(examinee.getEducation()) && examinee.getExperience() >= 3)
|| ("研究生".equals(examinee.getEducation()) && examinee.getExperience() >= 2);
}```

```private Predicate<Examinee> juniorCollege = new Predicate<Examinee>() {
public boolean apply(Examinee examinee) {
return "大专".equals(examinee.getEducation()) && examinee.getExperience() >= 5;
}
};

private Predicate<Examinee> undergraduate = new Predicate<Examinee>() {
public boolean apply(Examinee examinee) {
return "本科".equals(examinee.getEducation()) && examinee.getExperience() >= 3;
}
};

private Predicate<Examinee> postgraduate = new Predicate<Examinee>() {
public boolean apply(Examinee examinee) {
return "研究生".equals(examinee.getEducation()) && examinee.getExperience() >= 2;
}
};```

```private boolean canExam(Examinee examinee) {
return Predicates.or(juniorCollege, undergraduate, postgraduate).apply(examinee);
}```

canExam变得非常简洁。

## 2.3 更动态的配置

```private Map<Predicate<Double>, String> config = Maps.newHashMap();
{
config.put(new Predicate<Double>() {
@Override
public boolean apply(Double score) {
return score >= 60 && score < 70;
}
}, "及格");
config.put(new Predicate<Double>() {
@Override
public boolean apply(Double score) {
return score >= 70 && score < 80;
}
}, "良好");
config.put(new Predicate<Double>() {
public boolean apply(Double score) {
return score >= 80;
}
}, "优秀");
}```

```private String getLevel(Double score) {
for (Map.Entry<Predicate<Double>, String> entry : config.entrySet()) {
if (entry.getKey().apply(score)) {
return entry.getValue();
}
}
return "未知";
}```

82 篇文章29 人订阅

0 条评论

## 相关文章

1301

3276

### 懒惰的力量

（今天我在旧金山参加了Erlang factory 2015大会，增长了很多见识。参会的总结我过两天再写，很多思想需要时间沉淀。） 前段时间写了篇「永恒不变的魅...

3608

843

1012

### 只有JS基础扎实的攻城狮，才解得出的“密码”

HTML5学堂-码匠：虽然很不想面对，但是明天，的确是节后工作的开始，今天就一边解密一边“适应”一下代码吧！ Tips：如下的四道题目，是基于几家公司的面试真题...

39810

2005

3365

2117

1798