Java 中是否有与 Python 的 map 函数等效的函数?
我想轻松地将 A 类对象的集合(列表)转换为 B 类对象的集合,就像 Python 的 map 函数所做的那样。是否有任何“众所周知的”实现(某种库)?我已经在 Apache 的 commons-lang 中搜索过它,但没有成功。
I would like to easily transform a collection (list) of objects of class A to a collection of objects of class B, just as Python's map function does it. Is there any "well-known" implementation of this (some kind of library)? I've already searched for it in Apache's commons-lang but with no luck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
从Java 8开始,这可以通过
Stream API
使用适当的映射器Function
我们将使用它来转换类A< 的实例/code> 到类
B
的实例。伪代码如下:
这是一个具体示例,它将
String
的List
转换为List
Integer
使用Integer.valueOf(String)
作为映射器函数:输出:
对于
Java 的早期版本
,您仍然可以使用 来自 Google Guava 的FluentIterable
来替换Stream
并使用com.google.common.base.Function
而不是java.util.function.Function
作为映射器函数。前面的示例将被重写为下一个:
输出:
Starting from Java 8, it can be done thanks to the
Stream API
using an appopriate mapperFunction
that we will use to convert our instances of classA
to instances of classB
.The pseudo code would be:
Here is a concrete example that will convert a
List
ofString
to aList
ofInteger
usingInteger.valueOf(String)
as mapper function:Output:
For previous versions of
Java
, you can still useFluentIterable
from Google Guava to replace theStream
and usecom.google.common.base.Function
instead ofjava.util.function.Function
as mapper function.The previous example would then be rewritten as next:
Output:
仍然不存在的
函数式编程功能将添加到Java 8 - Project Lambda
我认为 Google Guava 最适合您目前的需求
still not exist
functional programming features will be added in Java 8 - Project Lambda
I think Google Guava is best for your needs now
这里提到了几个函数库,其中大部分可能涵盖了地图:
There are several functional libraries mentioned here, most of which probably cover map:
您可以尝试使用 guava,但您可能会发现,如果您使用匿名类,它会比仅使用循环更复杂且更长。
值得记住的是,Java 不是一种函数式语言,通常最好只使用循环。也许当Java有闭包时......叹息。
You can try guava, but you are likely to find that if you use an anonymous class its will be more complicated and longer than just using a loop.
Its worth remembering that Java is not a functional language and its often better to just use a loop. Perhaps when Java has closures .... sigh.
可以看看 Google 的 Guava 库:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Maps.html
Could take a look at Google's Guava library:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Maps.html
查看 lambdaj 及其 转换方法
Take a look at lambdaj and its convert method
从 Java 8 开始,Python 地图的 Java 等效项称为...地图!
此示例将整数列表转换为具有相应大小的数组列表:
您还可以在 map 内编写多个语句:
Since Java 8, the Java equivalent for Python's map is called ... map !
This examples converts a list of integers to a list of arrays with the corresponding size :
You can also write more than one statement inside map :
这是我的解决方案:
简单地,扩展此类定义函数 f 并调用列表上的方法映射。
This is my solution:
Simply, extends this class defining your function f and call the method map on the list.