Predicateインタフェースのサンプルです。
Functionインタフェースと同様、実装して他のクラスのメソッドに設定することで本来の能力を発揮します。
実装例です。以下のようなクラスがあるとします。
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の実装を書いてみました。
class WarriorPredicate implements Predicate<Warrior> {
@Override
public boolean apply(Warrior warrior) {
return warrior.hp > 0;
}
}
WarriorクラスのHPが0以上の場合にtrueを返すだけの実装です。
WarriorPredicateを以下のように使います。
Warrior w = new Warrior(100, 200, 300, 5000L);
WarriorHpPredicate whp = new WarriorHpPredicate();
System.out.println(whp.apply(w));
結果としてtrueが返されます。
最終更新:2014年01月11日 22:57