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?

Alex Miller
  • 65,227
  • 26
  • 112
  • 160
Fakrudeen
  • 5,242
  • 7
  • 38
  • 66
  • Interesting...C# doesn't even ship with `IEnumerable.Foreach` – Gabe Jan 23 '11 at 18:39
  • 2
    @Gabe - you are right about the pedantic point. I meant collection handling methods which take action. List.Foreach/Array.Foreach or Ienumerable.All etc. – Fakrudeen Jan 24 '11 at 05:45

3 Answers3

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

Aravind Yarram
  • 74,434
  • 44
  • 210
  • 298
  • I don't get one thing, Lambda expression is patented by Microsoft. What is the chance Java can use it? – hardywang Jul 17 '12 at 01:07
  • 1
    I laughed when I read that -- then found: http://www.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. – Dale Aug 22 '12 at 00:30
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.

kgrad
  • 4,462
  • 7
  • 33
  • 57
  • 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. – Fakrudeen Jan 24 '11 at 06:05
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.

Sean Patrick Floyd
  • 274,607
  • 58
  • 445
  • 566
Bryan Irace
  • 1,795
  • 2
  • 18
  • 38