Small Java 8+ utility for null-safe Optional access to Map values.
Replace:
Optional<String> name = Optional.ofNullable(map.get("user-1"));with:
Optional<String> name = OptionalMaps.getOptional(map, "user-1");Maven:
<dependency>
<groupId>io.github.j-util</groupId>
<artifactId>optional-map</artifactId>
<version>1.0.0</version>
</dependency>Use OptionalMaps.getOptional(map, key) when you only need one lookup:
Map<String, String> names = new HashMap<String, String>();
names.put("user-1", "Ada");
Optional<String> name = OptionalMaps.getOptional(names, "user-1");Use OptionalMaps.wrap(map) when you want a Map view with an extra
getOptional method:
Map<String, String> names = new HashMap<String, String>();
OptionalMap<String, String> optionalNames = OptionalMaps.wrap(names);
optionalNames.put("user-1", "Ada");
Optional<String> name = optionalNames.getOptional("user-1");getOptional returns Optional.empty() both when the key is absent and when the
key is present with a null value. You still need to use containsKey to
distinguish those cases.
./mvnw test