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]mapのキーの値をストリーム(anyMatch)でチェックして値が空なら例外スロー

Last updated at Posted at 2025-05-22

キーの値に空文字があれば、例外スロー

Map<String, String> map = Map.of(
	    "username", "admin",
	    "password", "",   // 空
	    "role", "editor"
	);

map.entrySet().stream()
    .filter(entry -> entry.getValue().isEmpty())
    .findFirst()
    .ifPresent(entry -> {
        throw new IllegalArgumentException("Empty value found for key: " + entry.getKey());
    });

キーの値にnull、または、空文字があれば、例外スロー

Map<String, String> map = Map.of(
	    "username", "admin",
	    "password", "",   // 空
	    "role", "editor"
	);

map.entrySet().stream()
    .filter(entry -> entry.getValue() == null || entry.getValue().isEmpty())
    .findFirst()
    .ifPresent(entry -> {
        throw new IllegalArgumentException("Empty value found for key: " + entry.getKey());
    });

補足:複数のキーを収集したい場合

Map<String, String> map = Map.of(
	    "username", "",  // 空
	    "password", "",   // 空
	    "role", "editor"
	);
    
List<String> invalidKeys = map.entrySet().stream()
    .filter(entry -> entry.getValue() == null || entry.getValue().isEmpty())
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

if (!invalidKeys.isEmpty()) {
    throw new IllegalArgumentException("Empty or null values found for keys: " + invalidKeys);
}

出力の一部

Caused by: java.lang.IllegalArgumentException: Empty or null values found for keys: [password, username]
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?