Skip to content

Instantly share code, notes, and snippets.

@max747
Created May 24, 2011 02:38
Show Gist options
  • Save max747/988053 to your computer and use it in GitHub Desktop.
Save max747/988053 to your computer and use it in GitHub Desktop.
map関数を実現したい
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);
}
}
@max747
Copy link
Author

max747 commented May 24, 2011

この方法だと type-safe にならない。微妙。

自前で List を定義して解決する、というアプローチもあるらしい。
http://jutememo.blogspot.com/2010/08/java-cons-nil-map-filter-foldr-foldl.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment