[英]How to create a method that accepts a boolean criteria and a lambda with arguments as a parameter in Java 8?
How to create a method that accepts a boolean criteria and a lambda with arguments as a parameter in Java 8? 在Java 8中,如何创建一个接受布尔条件和带有参数作为参数的lambda的方法?
For Example I have lot of this code. 例如,我有很多这样的代码。
if(something is true) {
foo("a", "b", 2)
}
if(something else is true) {
bar("hello", 1)
}
Want to create a method that accepts boolean and a lambda so I can factor out all the if checks so I can do something like this? 是否想要创建一个接受布尔值和lambda的方法,以便我可以排除所有if检查,以便可以执行类似的操作?
checkAndCAll(isValid, (a, b, c) -> { if(isValid) foo(a, b, c); })
checkAndCAll(isValid2, (a, b) -> { if(isValid2) bar(a, b, c); })
If there is something even cleaner please suggest 如果有更清洁的东西,请建议
Don't think the way you want to implement is good at all, but anyway - is this what you asked about? 根本不认为您想要实现的方法是好的,但是无论如何-这是您要的内容吗?
public static void main(String[] args) {
//how to use
checkAndCAll(true, new Object[]{"param1", "param2"}, p -> someMethod(p));
checkAndCAll(true, new Object[]{"param1", 2 , new AtomicInteger(124)}, p -> anotherMethod(p));
}
public static void checkAndCAll(boolean b, Object[] params, Consumer<Object[]> consumer) {
if (b) consumer.accept(params);
}
public static void someMethod(Object[] args) {
//some method to execute
System.out.println(args);
}
public static void anotherMethod(Object[] args) {
//some method to execute
System.out.println(args);
}
Can be even simpler, the paramaters can passed directly to the lambda: 甚至更简单,参数可以直接传递给lambda:
public static void main(String[] args) {
//how to use
checkAndCAll(true, () -> someMethod("param1,", "param2"));
checkAndCAll(false, () -> anotherMethod("param1", 123));
}
public static void checkAndCAll(boolean b, Runnable action) {
if (b) action.run();
}
public static void someMethod(Object param1, Object param2) {
//some method to execute
}
public static void anotherMethod(String param1, Integer param2) {
//some method to execute
}
But I think it's not very useful. 但是我认为这不是很有用。 The traditional 'if' requires comparable amount of code and in addition is more readable.
传统的“ if”需要相当数量的代码,而且可读性强。 In fact it only duplicates Java's 'if' statement semantics.
实际上,它仅复制Java的“ if”语句语义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.