Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Thanks to Java 8 you don't need to do the steps below to pass a function to a method, that's what lambdas are for, see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html" rel="noreferrer">Oracle's Lambda Expression tutorial</a>. The rest of this post describes what we used to have to do in the bad old days in order to implement this functionality.</p> <p>Typically you declare your method as taking some interface with a single method, then you pass in an object that implements that interface. An example is in commons-collections, where you have interfaces for Closure, Transformer, and Predicate, and methods that you pass implementations of those into. Guava is the new improved commons-collections, you can find equivalent interfaces there.</p> <p>So for instance, commons-collections has org.apache.commons.collections.CollectionUtils, which has lots of static methods that take objects passed in, to pick one at random, there's one called exists with this signature:</p> <pre><code>static boolean exists(java.util.Collection collection, Predicate predicate) </code></pre> <p>It takes an object that implements the interface Predicate, which means it has to have a method on it that takes some Object and returns a boolean.</p> <p>So I can call it like this:</p> <pre><code>CollectionUtils.exists(someCollection, new Predicate() { public boolean evaluate(Object object) { return ("a".equals(object.toString()); } }); </code></pre> <p>and it returns true or false depending on whether <code>someCollection</code> contains an object that the predicate returns true for.</p> <p>Anyway, this is just an example, and commons-collections is outdated. I just forget the equivalent in Guava.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload