有没有这样做的库:
public class Iterables{
private Iterables() {}
public static <T> int sum(Iterable<T> iterable, Func<T, Integer> func) {
int result = 0;
for (T item : iterable)
result += func.run(item);
return result;
}
}
public interface Func<TInput, TOutput> {
TOutput run(TInput input);
}
Run Code Online (Sandbox Code Playgroud)
Hen*_*son 10
基本上有两个有用的库可以帮助解决这个问题.Google Guava和Apache Commons Collections.
你要做的基本上是两个操作,首先是映射,然后是还原.我从未在任何程度上使用过Commons Collections,所以我不能告诉你更多关于这一点,但我知道至少在Google Guava中没有支持减少(或折叠)(见问题218).这不是很难添加自己(未经测试):
interface Function2<A, B> {
B apply(B b, A a);
}
public class Iterables2 {
public static <A, B> B reduce(Iterable<A> iterable,
B initial, Function2<A, B> fun) {
B b = initial;
for (A item : iterable)
b = fun.apply(b, item);
return b;
}
}
Run Code Online (Sandbox Code Playgroud)
这样你可以将它与Guavas Iterables.transform()结合使用:
class Summer implements Function2<Integer, Integer> {
Integer apply(Integer b, Integer a) {
return b + a;
}
}
class MyMapper<T> implements Function<T, Integer> {
Integer apply(T t) {
// Do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
然后(假设您已导入静态相关的类):
reduce(transform(iterable, new MyMapper()), 0, new Summer());
Run Code Online (Sandbox Code Playgroud)
另见这个问题.
Java不是一个功能性的语言,通常使用普通循环更简单,更快捷.
你可以写点像
List<String> list = /* ... */
int totalLength = Iterables.sum(list, new Func<String, Integer>() {
public Integer run(String input) {
return input.length();
}
});
Run Code Online (Sandbox Code Playgroud)
然而恕我直言,它更短,更简单,只是写.
List<String> list = /* ... */
int totalLength = 0;
for(String s: list) totalLength += s.length();
Run Code Online (Sandbox Code Playgroud)
当闭包成为Java的标准时,这将改变,但是现在循环通常是最好的方法.
由于Java 8现在正在收集集合很简单:
collection.stream().reduce(0, Integer::sum)
Run Code Online (Sandbox Code Playgroud)
不幸的是,流不可用于迭代,但总是可以转换.数组更容易:
LongStream.of(1, 2, 3).sum()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19220 次 |
| 最近记录: |