Stream API②

Stream API①の続き

Streamの終端操作

繰り返し処理

forEach

引数はConsumerインターフェース。

結果をまとめて取り出す終端操作

collect
要素を走査して結果を作成する。

        List<String> list = Arrays.asList("watanave", "hayashi", "tsuda", "seki", "sakai");

        //長さが5以上の要素に絞り、toListで戻り値をListにして返却。
        List<String> newList = list.stream()
            .filter(n -> n.length() > 5)
            .collect(Collectors.toList());

toList以外にも
toSet, joining, groupingByがある

・groupingBy
public class Main {
    
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();

        students.add(new Student("yamada", 100));
        students.add(new Student("harada", 50));
        students.add(new Student("gouda", 87));

        //キーに点数、値に対応する生徒のオブジェクトが入ったListでグルーピング
        Map<Integer, List<Student>> map = students.stream()
            .collect(Collectors.groupingBy(Student::getScore));

        //点数(キー)を元に任意の生徒を取り出す。
        List<Student> perfects = map.get(100);
        perfects.forEach(s -> System.out.println(s.getName()));
        //→ yamada

    }
}

toArray

全ての要素を配列にする。

        Stream<String> stream1 = Stream.of("a", "b", "c");
        Stream<Integer> stream2 = Stream.of(1,2,3,4);
        //streamからString型の配列に変換
        String[] strArr = stream1.toArray(String[]::new);
        //streamからInteger型の配列に変換
        Integer[] intArr = stream2.toArray(Integer[]::new);

reduce

値の集約処理をする。
引数はBInaryOperator
戻り値はOptional

public class Main {
    
    public static void main(String[] args) {
    // Integerのストリームを作成
    Stream<Integer>stream = Arrays.stream(new Integer[] { 1, 2, 3, 4});

    // reduceの戻り値はOptionalなので、Optionalでラッブする。
    Optional<Integer> total = stream.reduce((accum, value)->accum + value);
    
    System.out.println(total.get());    
    //→ 10
    }
}

まとめ

後半ちょっとだれて端折ってしまった部分があるが、大体わかった。
Qiitaで詳しく書かれた記事があったので、載せておく
qiita.com