Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is no closure yet in Java. Lambda expressions are coming in java 8. However, the only issue with what you're trying to translate is that it has state, which not something that lamba expressions will support i don't think. Keep in mind, it's really just a shorthand so that you can easily implement single method interfaces. You can however still simulate this I believe:</p> <pre><code>final AtomicInteger n = new AtomicInteger(0); IncrementByN v = (int x) -&gt; x + n.incrementAndGet(); System.out.println(v.increment(5)); System.out.println(v.increment(6)); </code></pre> <p>I have not tested this code though, it's just meant as an example of what might possibly work in java 8.</p> <p>Think of the collections api. Let's say they have this interface:</p> <pre><code>public interface CollectionMapper&lt;S,T&gt; { public T map(S source); } </code></pre> <p>And a method on java.util.Collection:</p> <pre><code>public interface Collection&lt;K&gt; { public &lt;T&gt; Collection&lt;T&gt; map(CollectionMapper&lt;K,T&gt; mapper); } </code></pre> <p>Now, let's see that without closures:</p> <pre><code>Collection&lt;Long&gt; mapped = coll.map(new CollectionMapper&lt;Foo,Long&gt;() { public Long map(Foo foo) { return foo.getLong(); } } </code></pre> <p>Why not just write this:</p> <pre><code>Collection&lt;Long&gt; mapped = ...; for (Foo foo : coll) { mapped.add(foo.getLong()); } </code></pre> <p>Much more concise right?</p> <p>Now introduce lambdas:</p> <pre><code>Collection&lt;Long&gt; mapped = coll.map( (Foo foo) -&gt; foo.getLong() ); </code></pre> <p>See how much nicer the syntax is? And you can chain it too (we'll assume there's an interface to do filtering which which returns boolean values to determine whether to filter out a value or not):</p> <pre><code> Collection&lt;Long&gt; mappedAndFiltered = coll.map( (Foo foo) -&gt; foo.getLong() ) .filter( (Long val) -&gt; val.longValue() &lt; 1000L ); </code></pre>
 

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