gre*_*rej 16 python java collections
我想轻松地将类A的对象集合(列表)转换为类B的对象集合,就像Python的map函数一样.是否有任何"知名"的实现(某种类型的库)?我已经在Apache的commons-lang中搜索过它,但没有运气.
从Java 8开始,可以通过Stream API使用我们将用于将类实例转换为类实例的适当映射器 来完成.FunctionAB
伪代码将是:
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());
Run Code Online (Sandbox Code Playgroud)
这里是将转换为一个具体的例子List中String的List的Integer使用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);
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
对于以前的版本中Java,你仍然可以使用FluentIterable从谷歌番石榴更换Stream和使用com.google.common.base.Function,而不是java.util.function.Function作为映射功能.
之前的示例将被重写为下一个:
List<Integer> output = FluentIterable.from(input)
.transform(
new Function<String, Integer>() {
public Integer apply(final String value) {
return Integer.valueOf(value);
}
}
).toList();
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
小智 6
仍然不存在
函数编程功能将添加到Java 8 - Project Lambda中
我认为Google Guava现在最适合您的需求
| 归档时间: |
|
| 查看次数: |
6556 次 |
| 最近记录: |