Lambda expressions of .NET in Java

徘徊边缘 提交于 2019-12-08 15:50:38

问题


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?


回答1:


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

  • http://commons.apache.org/collections/
  • http://functionaljava.org/
  • http://functionalj.sourceforge.net/
  • http://www.agical.com/jambda/

Or better look at Scala




回答2:


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.




回答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.



来源:https://stackoverflow.com/questions/4775627/lambda-expressions-of-net-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!