Skip to content

Instantly share code, notes, and snippets.

@kencharos
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kencharos/9655915 to your computer and use it in GitHub Desktop.
Save kencharos/9655915 to your computer and use it in GitHub Desktop.
Java8 - Listにfilter,mapなどの高階関数を追加してみる例
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
// 任意のListにmap, filterメソッドを追加する。
interface FunctionalList<T> extends List<T> {
default <R> FunctionalList<R> map(Function<T, R> f) {
FunctionalList<R> list;
try {
list = this.getClass().newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
throw new RuntimeException(ex);
}
for (Iterator<T> itr = this.iterator(); itr.hasNext();) {
list.add(f.apply(itr.next()));
}
return list;
}
default FunctionalList<T> filter(Predicate<T> pred) {
FunctionalList<T> list;
try {
list = this.getClass().newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
throw new RuntimeException(ex);
}
for (T t : this) {
if (pred.test(t)) {
list.add(t);
}
}
return list;
}
}
/**
* デフォルトメソッドとしてインターフェースに処理を切り出すことで、
* オーバライド扶養でArrayList, LinkedListなど好きなリストに実装を追加できる。
* が、実際にはそんなに使わないかも。streamと違って即時評価だし。
*/
public class FunctionalListImpl<T> extends ArrayList<T> implements FunctionalList<T>{
// test
public static void main(String[] args) {
FunctionalList<String> list = new FunctionalListImpl<>();
list.add("123");
list.add("456");
list.add("12");
list.add("45");
list.add("10000");
FunctionalList<Integer> result = list.filter(s -> s.length() > 2)
.map(Integer::parseInt);
System.out.println(result);
// 通常のstreamも併用可能。
System.out.println(result.stream().reduce(1, (a,b)-> a * b));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment