2 回答
TA贡献1827条经验 获得超4个赞
您可以创建一个包含所有可能的“正确”对的列表,然后在其上循环:
class Pair {
String sBody;
String fBody;
public String getsBody()
{
return sBody;
}
public String getfBody()
{
return fBody;
}
}
boolean check(List<Pair> list, String sBody, String fBody) {
for (Pair pair : list) {
if (pair.getsBody().equals(sBody) && pair.getfBody().equals(fBody)) {
return true;
}
}
return false;
}
当然,您仍然必须以某种方式填充此列表
TA贡献1828条经验 获得超6个赞
我会将字面量“ ball”,“ wall”等放入Enum。
public enum ObjectType {
BLOCK("block"),
BALL("ball"),
BONUS("bonus"),
WALL("wall");
private String objectType;
ObjectType(String objectType) {
this.objectType = objectType;
}
public String getObjectType() {
return objectType;
}
public boolean equals(String body) {
return objectType.equalsIgnoreCase(body);
}
}
然后,我会继续sBody和fBody一对。
public class Pair {
private final String fBody;
private final String sBody;
public Pair(String fBody, String sBody) {
this.fBody = fBody;
this.sBody = sBody;
}
public String getfBody() {
return fBody;
}
public String getsBody() {
return sBody;
}
@Override
public String toString() {
return "Pair{" +
"fBody='" + fBody + '\'' +
", sBody='" + sBody + '\'' +
'}';
}
}
然后,我将利用Java 8Predicate并创建谓词列表,如下所示:
public final class Predicates {
public static final List<Predicate<Pair>> PREDICATES =
Arrays.asList(
isBlockBall(),
isBlockBall()
// add rest of your predicates
);
private Predicates() {
// we do not need to instantiate this
}
public static Predicate<Pair> isWallBlock() {
return p -> ObjectType.WALL.equals(p.getfBody())
&& ObjectType.BLOCK.equals(p.getsBody());
}
public static Predicate<Pair> isBlockBall() {
return p -> ObjectType.BLOCK.equals(p.getfBody())
&& ObjectType.BALL.equals(p.getsBody());
}
}
然后,您可以测试您的状况,如下所示:
public class TestingPairs {
public static void main(String[] args) {
final String fBody = "block";
final String sBody = "ball";
Pair pair = new Pair(fBody, sBody);
final Optional<Predicate<Pair>> conditionMet = PREDICATES.stream().filter(pairPredicate -> pairPredicate.test(pair))
.findFirst();
if (conditionMet.isPresent()) {
// do your stuff
}
}
}
添加回答
举报