基本上有兩種有用的庫,可以幫助這一點; Google Guava和Apache Commons Collections。
你試圖做的基本上是兩個操作,第一個映射,然後減少。我從來沒有在任何程度上使用過Commons Collections,所以我不能告訴你更多的情況,但我知道至少在Google Guava中不支持減少(或摺疊)(參見Issue 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;
}
}
這樣,你可以用番石榴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
}
}
然後(前提是你」 ve導入static'ed相關類):
reduce(transform(iterable, new MyMapper()), 0, new Summer());
另請參閱this question。
你能解決你的例子嗎?我得到'方法適用於(A)函數不適用於fun.apply()行上的參數(B,A)`。 – 2016-04-19 17:43:25
也許吧。可能不會。答案是5歲,只是使用Java 8流:) – 2016-04-20 11:46:00