0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javaのstreamを使ってみよう!

Last updated at Posted at 2021-06-22

#streamを使ってみよう

###1. 使用するオブジェクト

class People { 
    private String name;
    private int age;
    private int gender;

public People(String name, int age, int gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
}

 public People(String name, int age, int gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;

}

public String toString() {

    return "People(name=" + name + ", age=" + age + ", gender=" + gender + ")";

}

public static List<People> getPeopleList() {
    return Arrays.asList(
        new People("any", 17, 2),
        new People("tom", 12, 1),
        new People("jerry", 15, 2),
        new People("scott", 18, 1),
        new People("paul", 20, 1)
    );
}

/** セッター、ゲッターは省略*/

2.stream使わない場合の例

    System.out.println("女性リスト");
    for (People people : People.getPeopleList()){
        if(people.getGender() == 2) {
            System.out.println(people);
        }
    }

3.上記と同じ処理をStreamを使った場合

    List<People> femaleList = People.getPeopleList().stream()
                      .filter(people -> people.getGender() == 2).collect(Collectors.toList());
    System.out.println("女性リスト");
    femaleList.forEach(System.out::println);

4.streamのsortedメソッドを使用例 (整列を行う)

    List<People> sortedList = People.getPeopleList().stream()
                                    .sorted(Comparator.comparing(People::getAge)).collect(Collectors.toList());
    System.out.println("年齢順リスト");
    sortedList.forEach(System.out::println);

5.streamのallMatchメソッドを使用例 (指定した条件にすべて項目が一致するか)

    //stream allMatch 利用 すべての項目が条件を一致するか
    boolean allMatch = People.getPeopleList().stream().allMatch(people -> people.getAge() > 12);
    System.out.println("全員の年齢が13歳以上であるか");
    System.out.println(allMatch);

6.streamのanyMatch メソッドを使用例 (指定した条件に一致する項目が存在するか)

    boolean anyMatch = People.getPeopleList().stream().anyMatch(people -> people.getAge() > 19);
    System.out.println("年齢が20歳以上の方がいるか");
    System.out.println(anyMatch);

7.streamのnoneMatch メソッドを使用例 (指定した条件にすべて項目が一致すしないか)

    boolean noneMatch = People.getPeopleList().stream().noneMatch(people -> people.getAge() < 10);
    System.out.println("年齢が10歳未満の方がいるか");
    System.out.println(noneMatch);

8.streamのmax メソッドを使用例 (最大値を持っているリストを取得)

    Optional<People> maxPeople = People.getPeopleList().stream().max(Comparator.comparing(People::getAge));
    if(maxPeople.isPresent()){
        System.out.println("一番延長者の方は");
        System.out.println(maxPeople.get());
    }

9.streamのminメソッドを使用例 (最小値を持っているリストを取得)

    Optional<People> minPeople = People.getPeopleList().stream().min(Comparator.comparing(People::getAge));
    if(minPeople.isPresent()){
        System.out.println("一番若い方は");
        System.out.println(minPeople.get());
    }

10.streamのcollect, Collectors.groupingByメソッドを使用例

    /** (特定フィールドでグループを作りマップを生成) */
    Map<Integer, List<People>> groupByGender = People.getPeopleList().stream()
                                .collect(Collectors.groupingBy(People::getGender));
    System.out.println("男性/女性 リスト");
    groupByGender.forEach((gender,peopleList) -> {
        System.out.println(gender);
        peopleList.forEach(System.out::println);
    });

    // stream 複合的に利用 //map -> mapping 名前だけをマッピングして返すのでジェネリクスでStringと指定
    Optional<String> oldestWomanName = People.getPeopleList().stream()
                           .filter(people -> people.getGender() == 2)
                           .max(Comparator.comparing(People::getAge))
                           .map(People::getName);
    System.out.println("女性の中で一番年長者の名前は");
    oldestWomanName.ifPresent(System.out::println);
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?