Java 中的函数式编程
如何在 Java 中模拟函数式编程,特别是执行诸如将函数映射到项目集合之类的操作?
map(func, new String[]{"a","b","c"});
什么是最不冗长的内容?尴尬的方式来做到这一点?
how can you emulate functional programming in java, specifically, doing things like map a function to a collection of items?
map(func, new String[]{"a","b","c"});
what's the least verbose & awkward way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 Java 中,所有函数式编程的尝试都会有一些冗长和/或笨拙,直到 Java 8。
最直接的方式是提供
Function
接口(例如 这一形式 Guava)并提供各种接受和调用它的方法(例如Collections#transfrom()
执行我认为您的map()
方法应该执行的操作)。不好的是,您需要实现
Function
并且经常使用匿名内部类来实现,该内部类的语法非常冗长:Lambda 表达式(在 Java 8 中引入)使这变得更加容易(并且可能更快)。使用 lambda 的等效代码如下所示:
或者更冗长,但更灵活:
All attempts of functional programming will have some part of verbose and/or awkward to it in Java, until Java 8.
The most direct way is to provide a
Function
interface (such as this one form Guava) and provide all kinds of methods that take and call it (such asCollections#transfrom()
which does what I think yourmap()
method should do).The bad thing about is that you need to implement
Function
and often do so with an anonymous inner class, which has a terribly verbose syntax:Lambda expressions (introduced in Java 8) make this considerably easier (and possibly faster). The equivalent code using lambdas looks like this:
or the more verbose, but more flexible:
我使用过 lambdaj 和 functionjava对于这类事情。而且可能还有其他人...
I have used lambdaj and functionaljava for this sort of things. And there are probably others...
只需用类或接口包装您想要在列表上应用的函数即可。
Just wrap the function you want to apply on the list with a class or an interface.
正如您所注意到的,Java 并不是为函数式编程而设计的,虽然您可以模拟它,但您必须真正想要这样做,即使它比使用 Java 中的标准编程更冗长、更尴尬。
以@Joachim 为例。
这使用 12 个符号,不包括右括号。在普通的 Java 中,同样的事情看起来是这样的。
这使用了 7 个符号。
您可以使用 Java 进行函数式编程,但您应该预料到它会比使用 Java 的自然编程风格更加冗长和尴尬。
As you note, Java isn't designed for functional programming and while you can emulate it, you have to really want to do this even if is it more verbose and more awkward than using standard programming in Java.
Take @Joachim's example.
This uses 12 symbols, not counting close brackets. The same thing in plain Java would look like.
This uses 7 symbols.
You can do functional programming in Java, but you should expect it to be more verbose and awkward than using the natural programming style of Java.
您可以下载计划于明年发布的 OpenJDK 8,并使用新的 Lambda 表达式进行函数式编程。请参阅http://macgyverdev.blogspot.se/2012/10/ function-programming-in-java.html 获取有关如何在 Collection API 中使用这些闭包以及它们如何与 Guava 和 LambdaJ 等 Java 8 之前的解决方案进行比较的示例。
You could download OpenJDK 8 which is scheduled for prodcution release next year and use the new Lambda Expressions for functional programming. See http://macgyverdev.blogspot.se/2012/10/functional-programming-in-java.html for examples of how these closures will be used in the Collection APIs and how they compare with pre-Java 8 solutions like Guava and LambdaJ.