mapとinject
Google Collectionsを使ったmapとinjectを作ってみました。
@SuppressWarnings("unchecked") static <IN, OUT, X extends Collection<OUT>> X map( Collection<IN> collection, Function<IN,OUT> f ) { try { X out = (X) collection.getClass().newInstance(); for ( IN i : collection ) out.add( f.apply(i) ); return out; } catch (InstantiationException e) { throw new IllegalArgumentException( "unsupported collection.", e ); } catch (IllegalAccessException e) { throw new IllegalArgumentException( "unsupported collection.", e ); } } static <X, IN> X inject( Collection<IN> collection, X context, Function<Pair<X,IN>,X> f ) { for ( IN i : collection ) context = f.apply( new Pair<X,IN>( context, i )); return context; }
使い方例。文字列のコレクションをmapで整数のコレクションに変換した後、injectで合計します。
// セットを作る。 Set<String> set = newHashSet("10","20","30"); // 要素をIntegerに変換 Set<Integer> converted = map(set, new Function<String,Integer>() { @Override public Integer apply(String arg) { return Integer.valueOf(arg); } }); // 合計する Integer total = inject( converted, 0, new Function<Pair<Integer,Integer>,Integer>() { @Override public Integer apply(Pair<Integer,Integer> arg ) { return arg.getA() + arg.getB(); } } ); System.out.println( total );
実行結果です。
60