LoginSignup
2
3

More than 5 years have passed since last update.

Stringから文字のストリームを生成する

Posted at

文字列を文字のリストとして表現する関数型言語では、個々の文字に対する処理をmapで書けるので便利です(Haskellとか)。同じことをJavaのStream APIでやろうとした時に手間取ったのでコード例の形でメモしておきます。
結論から言えば、chars()mapToObj()とキャストを使います。

コード例

class Main {
    public static void main(String[] args) {
        String str = "abcde";
        str.chars()
           .mapToObj(i -> (char)i)
           .map(Character::toUpperCase)
           .forEach(System.out::println);
    }
}

出力

$ java Main
A
B
C
D
E

何はともあれループを使わなくて済んだのは良かったです。

参考リンク

Why is String.chars() a stream of ints in Java 8? - Stack Overflow

2
3
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
2
3