首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有没有与Python的map函数等效的Java函数?

有没有与Python的map函数等效的Java函数?
EN

Stack Overflow用户
提问于 2010-12-21 21:21:20
回答 8查看 9.8K关注 0票数 18

我想轻松地将类A的对象集合(列表)转换为类B的对象集合,就像Python的map函数所做的那样。有没有什么“知名”的实现(某种类库)?我已经在Apache的commons-lang中搜索过它,但没有找到。

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2010-12-21 21:32:09

仍然不存在

将在Java 8 - Project Lambda中添加函数式编程功能

我认为Google Guava现在最适合您的需求

票数 5
EN

Stack Overflow用户

发布于 2016-10-27 00:51:32

Java8开始,这要归功于Stream API使用一个适当的映射器 Function,我们将使用它将A类的实例转换为B类的实例。

伪代码将是:

代码语言:javascript
复制
List<A> input = // a given list of instances of class A
Function<A, B> function = // a given function that converts an instance 
                          // of A to an instance of B
// Call the mapper function for each element of the list input
// and collect the final result as a list
List<B> output = input.stream().map(function).collect(Collectors.toList());

下面是一个具体的示例,它将使用Integer.valueOf(String)作为映射器函数将StringList转换为IntegerList

代码语言:javascript
复制
List<String> input = Arrays.asList("1", "2", "3");
List<Integer> output = input.stream().map(Integer::valueOf).collect(Collectors.toList());
System.out.println(output);

输出:

代码语言:javascript
复制
[1, 2, 3]

对于以前版本的Java ,您仍然可以使用Google Guava中的FluentIterable来替换Stream,并使用com.google.common.base.Function代替java.util.function.Function作为<代码>e129映射器函数。

上一个示例将被重写为

代码语言:javascript
复制
List<Integer> output = FluentIterable.from(input)
    .transform(
        new Function<String, Integer>() {
            public Integer apply(final String value) {
                return Integer.valueOf(value);
            }
        }
    ).toList();

输出:

代码语言:javascript
复制
[1, 2, 3]
票数 10
EN

Stack Overflow用户

发布于 2010-12-21 21:26:58

有几个提到here的函数库,其中大部分可能涵盖了map:

http://www.cs.chalmers.se/~bringert/hoj/程序员(包括Java5.0泛型支持)。很少的文档。

http://jakarta.apache.org/commons/sandbox/functor/看起来不像是被维护的,不支持泛型。很少的文档。

http://devnet.developerpipeline.com/documents/s=9851/q=1/ddj0511i/0511i.html库。

http://functionalj.sourceforge.net

http://www.functologic.com/orbital/

java的http://jga.sourceforge.net/编程(包括泛型)。期待更多的文档,也许能更好地组织API.

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4499670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档