12
19

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 5 years have passed since last update.

JavaAdvent Calendar 2017

Day 19

Java Stream APIチートシート

Last updated at Posted at 2017-12-08

Stream超便利。Stream正義、そしてStreamすぐ忘れる。ということでチートシートを作成しました。
よろしくご査収ください。

全てに処理を行う(List編)

Arrays.asList("ほんと", "世の中", "世知辛い").stream().forEach(s -> System.out.println(s));
Arrays.asList("まじまじ", "ホント", "世知辛い").stream().forEach(System.out::println);

全てに処理を行う(Map編)

Collections.emptyMap().entrySet()
  .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));

特定のものだけ処理を行う。

Arrays.asList("恋", "愛", "金", "夢").stream()
  .filter(s -> s.equals("愛")).forEach(System.out::println);

型変換する。

Arrays.asList("1", "2", "3", "5").stream()
  .map(s -> Integer.valueOf(s)).forEach(System.out::println);

特定範囲の数字に対して処理する。

IntStream.range(0, 10).map(i -> i*2).toArray();

List→Mapにする。

Arrays.asList("SU-METAL DEATH!", "YUIMETAL DEATH!", "MOAMETAL DEATH!").stream()
  .map(s -> s.split(" ",2)).filter(a -> 2 == a.length)
  .collect(Collectors.toMap(a->a[0], a->a[1]));

マルチスレッドで高速に処理する。

Arrays.asList("恋", "愛", "金", "夢").parallelStream()
  .findFirst(s -> s.equals("愛"));

List結合

Arrays.asList("愛,それは,甘く","愛,それは,強く","愛,それは,尊く").stream()
  .map(s -> s.split(",")).flatMap(a -> Arrays.asList(a).stream())
  .collect(Collectors.toList());

長くなったら変数化。

Function<String, String> toHakata = s -> {
    return s + "とよ。";
};
Arrays.asList("そぎゃんこつなか").stream().map(toHakata);

他にもあったら

コメント、プルリクください。

12
19
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
12
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?