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?

JavaでStringのreplaceメソッド実行時にNullPointerException発生させたくない

Posted at

実装例1

// nullがどこかの処理で設定されている前提で
String str = null;

// Optional.ofNullableメソッドの引数がnullの場合にorElseメソッドの引数の値を返す
String result = Optional.ofNullable(str)
        .map(s -> s.replace("\n", "").replace("\r", ""))
        .orElse(null);

System.out.println(result); // null

実装例2

プライベートメソッド追加

private static String safeReplace(String str, String replacement) {
    // nullだったらreplaseメソッド実行されない
    return (str == null) ? null : str.replace("\n", replacement).replace("\r", replacement);
}

プライベートメソッド呼び出している処理の一部

// nullがどこかの処理で設定されている前提で
String str = null; 

String result = safeReplace(str, "");  

System.out.println(result); // null
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?