1.代码
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);
}
}
2.当然,与if-else差不多,但是map查询比较会较if-else少。