LoginSignup
1
0

More than 5 years have passed since last update.

具体的な条件で使用するStream

Last updated at Posted at 2018-04-23

StreamAPI 関連のブログ記事とかを見ても
示し合わせたようにみんな超シンプルに String しか使ってなくて面白味がない。

〜.class単位でソートしたいときだってあるし、
特定の値でグループ化したうえで処理したいことだってある。

「そんな具体的な条件でStreamを使おう」という内容です。

Person.class

public class Person {
    private String name;
    private String gender;
    private double height;

    public Person(String name, String gender, double height) {
        this.name = name;
        this.gender = gender;
        this.height = height;
    }

    public String getName() {
        return name;
    }

    public String getGender() {
        return gender;
    }

    public double getHeight() {
        return height;
    }
}


// Streamで処理するList
List<Person> people = Arrays.asList(
        new Person("alex", "male", 161.7),
        new Person("boss", "male", 171.4),
        new Person("chaos", "male", 154.3),
        new Person("akari", "female", 135.4),
        new Person("big mam", "female", 151.2),
        new Person("cinnamon", "female", 148.7),
        new Person("jhon", "them", 187.5),
        new Person("wall", "them", 157.9),
        new Person("owner", "them", 187.8));
// とりあえずシャッフルしておく。
Collections.shuffle(people);

型を変換する

更新予定

グループ化

グループ化は Collectors.groupingBy(classifier) を使います。
並列ストリームの場合は Collectors.groupingByConcurrent(classifier)です。

性別でグループ化して名前のListを取得する

// 性別ごとに名前のListを作る
Map<String, List<String>> genMapped = people.stream()
        .collect(Collectors.groupingBy(Person::getGender, Collectors.mapping(Person::getName, Collectors.toList())));

System.out.println(genMapped);
// {them=[jhon, owner, wall], female=[akari, big mam, cinnamon], male=[alex, boss, chaos]}

1
0
2

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
1
0