user1870400
user1870400

Reputation: 6364

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?

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?

  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

Upvotes: 0

Views: 584

Answers (2)

manicka
manicka

Reputation: 204

Can be even simpler, the paramaters can passed directly to the 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. In fact it only duplicates Java's 'if' statement semantics.

Upvotes: 1

Vitaliy Moskalyuk
Vitaliy Moskalyuk

Reputation: 2583

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);
}

Upvotes: 1

Related Questions