早速例です。Predicateと同様以下のようなクラスがあるとします。
class Warrior {
public Warrior(Integer hp, Integer atk, Integer def, Long exp){
this.hp = hp;
this.atk = atk;
this.def = def;
this.exp = exp;
}
Integer hp;
Integer atk;
Integer def;
Long exp;
}
Predicateインタフェースの実装を2つ定義します。
class WarriorHpPredicate implements Predicate<Warrior> {
@Override
public boolean apply(Warrior warrior) {
return warrior.hp > 0;
}
}
class WarriorExpPredicate implements Predicate<Warrior> {
@Override
public boolean apply(Warrior warrior) {
return warrior.exp < 9999999;
}
}
2つのPredicateの実装を利用したPredicatesのサンプルコードは以下になります。
public void predicates01() {
Warrior w = new Warrior(100, 200, 300, 5000L);
WarriorHpPredicate whp = new WarriorHpPredicate();
WarriorExpPredicate wexp = new WarriorExpPredicate();
System.out.println(Predicates.and(whp, wexp).apply(w));
}
Warriorオブジェクトは2つの条件に合致しているため、trueが返却されます。
Predicatesには他にも以下のメソッドがあります。他にもありますがここでは割愛します。
Predicates.or
Predicates.not
上記メソッドはandも含め3個以上のPredicateの実装を引数にとる事ができます。
最終更新:2014年01月11日 23:22