我想轻松地将类A的对象集合(列表)转换为类B的对象集合,就像Python的map函数所做的那样。有没有什么“知名”的实现(某种类库)?我已经在Apache的commons-lang中搜索过它,但没有找到。
发布于 2010-12-21 21:32:09
仍然不存在
将在Java 8 - Project Lambda中添加函数式编程功能
我认为Google Guava现在最适合您的需求
发布于 2016-10-27 00:51:32
从Java8开始,这要归功于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());下面是一个具体的示例,它将使用Integer.valueOf(String)作为映射器函数将String的List转换为Integer的List:
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 Guava中的FluentIterable来替换Stream,并使用com.google.common.base.Function代替java.util.function.Function作为<代码>e129映射器函数。
上一个示例将被重写为:
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]发布于 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.
https://stackoverflow.com/questions/4499670
复制相似问题