Given a Map<K, Object>, I'm returning Map<K, String> or throwing an Exception for at least one non-String value.
private static <K> Map<K, String> validate(final Map<K, Object> map)
throws NonStringValueException {
final List<Object> invalidValues = new ArrayList<Object>();
final Map<K, String> result = new HashMap<K, String>();
for(Map.Entry<K, Object> entry : map.entrySet()) {
if(!(entry.getValue() instanceof String)) {
invalidValues.add(entry.getValue());
}
else {
result.put(entry.getKey(), (String) entry.getValue());
}
}
if(!invalidValues.isEmpty()) {
throw new NonStringValueException("Invalid Values:
must be `String` type: " + invalidValues);
}
return result;
}
Besides using instanceOf and then casting, is there a better way to write this method?