这里使用谓词和过滤器的更实用的方法。
public class StudentCredit {
public static void main(String[] args) {
List<Student> students = Arrays.asList(new Student(5), new Student(5),
new Student(6), new Student(6), new Student(9));
final int six = 6;
Predicate<Student> hasSixCredits = new Predicate<Student>() {
public boolean isTrue(Student object) {
return object.getCredit() == six;
}
};
List<Student> studentsWithSix = Filter.filter(students, hasSixCredits);
System.out.println("Number of students with " + six + " credits is: "
+ studentsWithSix.size());
Filter<Student> filter = new Filter<Student>();
List<Student> result = filter.apply(students);
System.out.println("Apply empty filter. #students: " + result.size());
List<Student> otherResult = filter.setPredicate(hasSixCredits).apply(
students);
System.out.println("Apply 6-credits filter. #students: " + otherResult.size());
}
}
class Student {
private final int credit;
public Student(int credit) {
this.credit = credit;
}
public int getCredit() {
return credit;
}
}
interface Predicate<T> {
/* tautology - always true */
public static final Predicate<Object> ALWAYS_TRUE = new Predicate<Object>() {
public boolean isTrue(Object object) {
return true;
}
};
/* contradiction - always false */
public static final Predicate<Object> ALWAYS_FALSE = new Predicate<Object>() {
public boolean isTrue(Object object) {
return false;
}
};
public boolean isTrue(T object);
}
final class Filter<T> {
private Predicate<? super T> predicate = Predicate.ALWAYS_TRUE;
public Filter() {
}
public Filter<T> setPredicate(Predicate<? super T> predicate) {
this.predicate = predicate;
return this;
}
public List<T> apply(List<T> list) {
List<T> filtered = new ArrayList<T>();
for (T element : list)
if (predicate.isTrue(element))
filtered.add(element);
return filtered;
}
public static <T> List<T> filter(List<T> list, Predicate<? super T> predicate) {
return new Filter<T>().setPredicate(predicate).apply(list);
}
}
使用这种方法,您还可以创建其他谓词,而无需进行计数。您唯一关心的是谓词的逻辑。