LoginSignup
9
9

More than 5 years have passed since last update.

ThrowingStreamを使ってみる

Last updated at Posted at 2016-07-06

ThrowingStreamを使ってみる

ThrowingStreamについて

Java 8で追加されたStream APIのfilterやmapなどのメソッドでは、チェック例外(Exceptionの派生クラス)をスローするような処理は書けませんが、面白いAPIを見つけました。

このAPIを使ってみました。

サンプルのAクラス

変なサンプルですが、Aクラスを用意します。

A.java
class A {
    public static String s2(String s) throws IOException {
        if("a".equals(s)){
            throw new IOException("Bad!");
        }
        return s + s;
    }
    public static String s3(String s) {
        return s + s + s;
    }
}

通常のStream APIを使うと…

A#s2()はIOExceptionをスローするため、次のように書く必要があり、コードが読みづらいです。

java
    Stream.of("a", "b")
        .map(s->{
            try{
                return A.s2(s);
            }catch(IOException e){
                throw new UncheckedIOException(e);
            }
        }).forEach(System.out::println);

ThrowingStreamを使うと…

ThrowingStreamを使うと、次のようにコードがすっきりします。

java
    try {
        ThrowingStream.of(Stream.of("a", "b"), IOException.class)
            .map(A::s2)
            .forEach(System.out::println);
    } catch (IOException ex) {
        ex.printStackTrace(System.err);
    }

ThrowingFunctionを活用してみる…

次は、A#s2()の呼び出しでIOExceptionがスローされたら、代わりにA#s3()を呼び出すコードです。
try~catchを使わないのが特徴ですが、可読性はどうなんですかね…

java
class B {
    public static String go(String s){
        final ThrowingFunction<String, String, IOException> func = A::s2;
        return func.fallbackTo(A::s3).apply(s);
    }
}

B.go("a") を実行すると、 aaa が返ってきます。
例外の出力は一切ありません。

9
9
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
9
9