Java中有没有等同于Python的map函数?

18 投票
8 回答
13378 浏览
提问于 2025-04-16 08:50

我想要简单地把一堆属于A类的对象变成一堆属于B类的对象,就像Python里的map函数那样。有没有什么“大家都知道”的实现方法(比如某个库)?我已经在Apache的commons-lang里找过了,但没有找到。

8 个回答

3

这里提到了一些功能性库,很多可能都涉及到“map”这个概念:

http://www.cs.chalmers.se/~bringert/hoj/ 这是一个程序员用的库(支持Java 5.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/

http://jga.sourceforge.net/ 这是一个用Java编程的库(支持泛型)。希望能有更多的文档,可能还需要更好的API组织。

10

Java 8开始,我们可以通过Stream API来实现这个功能,使用一个合适的映射器 Function,将我们的类A的实例转换为类B的实例。

伪代码大概是这样的:

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());

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

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

输出结果:

[1, 2, 3]

对于早期版本Java,你仍然可以使用来自Google GuavaFluentIterable来替代Stream,并使用com.google.common.base.Function作为映射函数

之前的例子可以改写成:

List<Integer> output = FluentIterable.from(input)
    .transform(
        new Function<String, Integer>() {
            public Integer apply(final String value) {
                return Integer.valueOf(value);
            }
        }
    ).toList();

输出结果:

[1, 2, 3]
5

仍然不存在

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

我觉得Google Guava现在最适合你的需求

撰写回答