Lambda expressions of .NET in Java
Asked Answered
D

3

10

I recently moved from C# to Java [again]. But I badly miss lambda expressions and things like IEnumerable.Foreach of C#. So I am looking for a lambda expression library in Java.

are there better libraries than LambdaJ?

Also is clojure directly inlinable in Java programs? That is can I mix clojure code in Java functions?

Denaedenarius answered 23/1, 2011 at 18:37 Comment(2)
Interesting...C# doesn't even ship with IEnumerable.ForeachChemisorb
@Chemisorb - you are right about the pedantic point. I meant collection handling methods which take action. List<T>.Foreach/Array.Foreach or Ienumerable<T>.All etc.Denaedenarius
G
13

Java 8 might have lambda support natively. Until then you can use a combination of anonymous inner classes and libraries like google-guava. Below are other libraries that you can look into

Or better look at Scala

Grief answered 23/1, 2011 at 18:48 Comment(2)
I don't get one thing, Lambda expression is patented by Microsoft. What is the chance Java can use it?Aconite
I laughed when I read that -- then found: google.com/patents/US20070044083 ... C# is not close to the first language to have lambda expressions. The patent must be one of those silly "I don't want to get sued for doing this thing that everyone has used" patents.Ermentrude
Z
3

The equivalent foreach loop in Java is structured like this

List<Foo> fooList = // some list containing foos
for (Foo foo : fooList){
    // do stuff
}

There are no lambda expressions in Java, however if you can wait until Java8 they are adding closures. The closest you can get are anonymous inner classes.

Zipnick answered 23/1, 2011 at 18:41 Comment(1)
Thanks - but I didn't mean the equivalent of C#'s foreach keyword. I meant SomeCollection.ForEach(closure). Later part of the answer is useful though, although a. inner classes are verbose.Denaedenarius
S
3

The Google Guava library contains Function and Predicate classes that can be used to emulate lambda-like functionality. As kgrad mentions above, you can create anonymous instances of each one.

http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Function.html
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Predicate.html

Although you could easily write classes like these yourself, Guava contains a lot of helper methods that utilize functions and predicates for doing things like transforming or filtering all different types of iterables: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html

Note: I realize that Pangea already posted a link to Google Guava above, but I had already started writing this post and thought it would still be useful to provide the links.

Superheat answered 23/1, 2011 at 18:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.