JAX
JAX

Reputation: 1620

Support for lambda expressions in Java 8

In C# when we wanna create methods that can take in lambda expressions as arguments we can use either Action or Func<T> depending on the situation. The new Java 8 has added support for lambdas but I couldn't find any decent example on how to use that. So assuming that I wanna create a method in Java similar to this C# one:

public static Boolean Check (String S, Func<String, Boolean> AnAction) {
     return AnAction(S);
} 

How exactly could this be written in Java then ?

Upvotes: 1

Views: 235

Answers (2)

Eran
Eran

Reputation: 393771

If your lambda returns a boolean, you can use a Predicate :

public static boolean check (String s, Predicate<String> pred)
{
    return pred.test(s);
}

Or you can use a general Function :

public static Boolean check (String s, Function<String,Boolean> func)
{
    return func.apply(s);
}

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213193

Lambda expression at runtime is basically an instance of a functional interface. So, any method that takes a functional interface type as parameter can be passed a lambda expression.

For e.g., Java 8 defines many ready-to-use functional interfaces in java.util.function package. You can use one of them. Or even you can create your own. Equivalent one for your use-case would be java.util.function.Function<T, R>. For boolean return value, you can directly use Predicate though.

So suppose you've your method defined like this:

public static boolean check(String testString, Predicate<String> predicate) {
    return predicate.test(testString);
}

And then you can invoke it like this:

check("Some String to test predicate on", s -> s.length() > 10);

Upvotes: 5

Related Questions