1

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 ?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
JAX
  • 1,540
  • 3
  • 15
  • 32
  • 1
    possible duplicate of [Java's equivalents of Func and Action](http://stackoverflow.com/questions/1184418/javas-equivalents-of-func-and-action) – ChiefTwoPencils Aug 13 '14 at 16:46
  • http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html has few nice examples of how to use lambdas, the nicest one there IMHO is Approach 8. – Pshemo Aug 13 '14 at 16:50

2 Answers2

5

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);
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

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);
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • I think OP is more interested in how to call the method, at least that's how I interpreted his question since the method it self needs no lambda but the calling. – Rand Random Aug 13 '14 at 16:51
  • @RandRandom `How exactly could this be written in Java then ?` implies OP wants to know how to define methods that accept lambda expressions in Java. – Eran Aug 13 '14 at 16:54