Created
May 24, 2011 02:38
-
-
Save max747/988053 to your computer and use it in GitHub Desktop.
map関数を実現したい
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Collection; | |
public class Utils { | |
public static <S, T, R extends Collection<T>> R map(Collection<S> target, Function<S, T> function, Class<R> clazz) { | |
R newCollection = null; | |
try { | |
newCollection = clazz.newInstance(); | |
} catch (InstantiationException e) { | |
throw new RuntimeException(); | |
} catch (IllegalAccessException e) { | |
throw new RuntimeException(); | |
} | |
for (S element : target) { | |
T mapped = function.exec(element); | |
newCollection.add(mapped); | |
} | |
return newCollection; | |
} | |
public interface Function<In, Out> { | |
public Out exec(In input); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
この方法だと type-safe にならない。微妙。
自前で List を定義して解決する、というアプローチもあるらしい。
http://jutememo.blogspot.com/2010/08/java-cons-nil-map-filter-foldr-foldl.html