LoginSignup
26
21

More than 5 years have passed since last update.

Java8 Stream#collect

Last updated at Posted at 2014-03-20

Stream -> List がちょっと複雑だったからメモ

単純に変換可能だった。

Stream<E>#collect
Stream.of(1,2,3,4,5,6,7,8,9,10,11).collect(Collectors.toList());

IntStream に変えてみたら面倒になった。

IntStream#collect
IntStream.of(1,2,3,4,5,6,7,8,9,10,11).collect(ArrayList<Integer>::new,(a,b)->{a.add(b);},null);

長いと思ったので Stream<E> に変換してみた

Stream#collect
IntStream.of(1,2,3,4,5,6,7,8,9,10,11).mapToObj(Integer::valueOf).collect(Collectors.toList());

Utilクラスを作成してみる

ListUtil
class ListUtil {
    public static <T> void add(List<T> list, T value) {
        list.add(value);
    }

    public static <T> List<T> gen() {
        return new ArrayList<>();
    }

}
IntStream#collect
IntStream.of(1,2,3,4,5,6,7,8,9,10,11).collect(ListUtil::gen,ListUtil::add,null);

よくみたら boxed てものがあった。

Stream#collect
IntStream.of(1,2,3,4,5,6,7,8,9,10,11).boxed().collect(Collectors.toList());

この例は通し番号だからこういうことも

Stream#collect
IntStream.range(1,11).boxed().collect(Collectors.toList());
26
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
21