Java Magazine, Mar/Apr 2018
ORACLE COM JAVAMAGAZINE MARCH APRIL 2018 63 jvm languages As a reminder the closure syntax in Groovy uses braces to wrap the entire expression and if you are using a single argument closure without defining a dummy name the variable it is used by default These days Java 8 and above can do this same procedure using streams The analogous code in Java would be this List Integer nums Arrays asList 3 1 4 1 5 9 2 6 5 int sum nums stream mapToInt n n 2 filter n n 3 0 sum System out println The sum is sum The mapToInt method on Stream takes a lambda expression representing a java util function Function interface and produces an IntStream The filter method takes a java util function Predicate as an argument and returns a new IntStream which includes the sum method to get the final result If you want to use streams in Groovy the only diference is that where the Java methods expect functional interfaces you provide Groovy closures as in the following example assert nums stream mapToInt it 2 filter it 3 0 sum 36 Here the arguments to the Java stream methods mapToInt and filter are Groovy closures If you use Groovy versions that support the new Parrot parser you can supply Java lambdas instead in any of the legal forms For example
You must have JavaScript enabled to view digital editions.