为运算符定义接口,并将实例放在Map容器中,这样就可以将字符串和运算符之间做一个映射,完成转换。

public class CompareUtil {
    public interface Operation {
        boolean calculate(int a, int b);
    }

    public static final Map<String, Operation> opMap = new HashMap<>();
    static {
        opMap.put(">", ((a, b) -> a > b));
        opMap.put(">=", ((a, b) -> a >= b));
        opMap.put("<", ((a, b) -> a < b));
        opMap.put("<=", ((a, b) -> a <= b));
        opMap.put("=", ((a, b) -> a == b));
    }
}

然后测试

public class test {
    public static void main(String[] args) {
        String str = ">";
        int ab = 3;
        int ac = 2;
        boolean res = CompareUtil.opMap.get(str).calculate(ab,ac);
        System.out.println("ssssssss" + res);
    }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐