Sasha Shpota
Sasha Shpota

Reputation: 10300

Assert that map contains not null vales by given keys

I have a code that consumes map of properties with string keys which represents some kind of context. And I want this code to fail if the map does not contain some of the required properties.

The corresponding code might look like this:

SomeResultType businessMethod(Map<String, String> context) {
    Assert.isTrue(context.containsKey("A"), "A property must not be empty");
    Assert.isTrue(context.containsKey("B"), "B property must not be empty");
    Assert.isTrue(context.containsKey("C"), "C property must not be empty");
    // ...
}

I wrote a simple replacement by myself with signature like this

public static <K, V> void mapContainsKeys(Map<K, V> map, K... keys)

But I think that something like this must be already implemented somewhere. So I'm searching for library replacement of this code.

It would be great if Spring guys implemented something like this in org.springframework.util.Assert.

Upvotes: 1

Views: 2292

Answers (2)

rptmat57
rptmat57

Reputation: 3787

if you want to just check that a map contains a list of keys, use this:

map.keySet().containsAll(keys)

if you want more details, to know which ones were missing:

Set<String> missingKeys = new HashSet<>(keys);
missingKeys.removeAll(map.keySet());

and then:

if (!missingKeys.isEmpty()) {
    throw new IllegalArgumentException(missingKeys + " keys missing");
}

Upvotes: 2

The fact that you had to write a helper method means that you are probably manipulating maps all over your code. Looks like a code smell to me, you should probably map your properties to an object that you can validate once and pass everywhere.

Since you are using Spring, and if you are using Spring Boot (most people do nowadays), you can use @ConfigurationProperties to map your configuration properties to an object.
This way you can also add validation like @javax.validation.constraints.NotNull and make sure your properties are valid.

Upvotes: 1

Related Questions