A more powerful alternative to
Optional<T>for handling null values safely, cleanly and functionally in Java.
NullSafe<T> is a class designed to encapsulate values that can be null, offering chainable methods, validations, error recovery, functional adapters and support for collections, maps and strings.
It prevents dreaded NullPointerException and provides a rich and flexible API for developing clean, safe and expressive code.
| Feature | Description |
|---|---|
| β Functional chaining | Methods like map, flatMap, filter, etc. |
| β Error recovery | .recover(...), .recoverWith(...) |
| β Integrated validations | .validate(pred, msg), .validate(pred, () -> ex) |
| β Type conversions | .toOptional(), .toResult("error"), .stream() |
| β Custom adapters | .adapt(adapter) |
| β Integrated logging | .logIfPresent(...), .logIfAbsent(...)) |
| β Multiple value combination | .combine(a, b, (x, y) -> x + y) |
| β Collections and maps usage | Static methods like filterNonNull(...), mapNonNullValues(...) |
| β Specialized primitive types | NullSafeInt, NullSafeLong, NullSafeDouble, NullSafeFloat, NullSafeBoolean, NullSafeByte, NullSafeShort |
This project has been fully configured and optimized for Java 11, ensuring broad compatibility and future-proof development:
- β Configuration Unified: All Maven compiler settings consistently use Java 11
- β
Compilation: Built with
--release=11flag for backward compatibility - β Test Coverage: 73 tests passing (37 primitive tests + 36 core tests)
- β API Compatibility: All existing features fully maintained
- β Performance: Optimized for Java 11 runtime environment
Recent Improvements: Fixed pom.xml inconsistencies by unifying maven.compiler.source, maven.compiler.target, and plugin configurations to Java 11, ensuring consistent build behavior.
The library works seamlessly with Java 11+ while maintaining full API compatibility with newer Java versions.
NullSafe.of(" hello world ")
.map(String::trim)
.filter(s -> s.length() > 5)
.map(String::toUpperCase)
.recover(ex -> "DEFAULT VALUE")
.validate(s -> s.contains("HELLO"), "Does not contain 'HELLO'")
.ifPresent(System.out::println);You can easily convert between NullSafe and Result<T, E>:
Result<String, String> result = NullSafe.of("value").toResult("Value not found");
result.ifSuccess(System.out::println)
.ifFailure(err -> System.err.println("Error: " + err));In addition to NullSafe<T>, the library includes specialized classes for safely handling primitive types:
NullSafeInt- Safe handling ofIntegervaluesNullSafeLong- Safe handling ofLongvaluesNullSafeDouble- Safe handling ofDoublevaluesNullSafeFloat- Safe handling ofFloatvaluesNullSafeBoolean- Safe handling ofBooleanvaluesNullSafeByte- Safe handling ofBytevaluesNullSafeShort- Safe handling ofShortvalues
// NullSafeInt
int result = NullSafeInt.of(42)
.ifPresent(value -> System.out.println("Value: " + value))
.orElse(0);
// NullSafeDouble with validations
double price = NullSafeDouble.of(product.getPrice())
.validate(p -> p > 0, "Price must be positive")
.orElse(0.0);
// NullSafeBoolean for conditional logic
boolean isValid = NullSafeBoolean.of(userInput)
.orElse(false);
// Handling extreme values
NullSafeLong.of(Long.MAX_VALUE)
.orElseThrow(() -> new RuntimeException("Value too large"));
NullSafeDouble.of(Double.NaN)
.ifPresent(value -> System.out.println("Is NaN: " + value))
.orElseGet(() -> 0.0);- Performance: Avoid automatic boxing/unboxing
- Memory: Lower memory usage than boxed types
- Safety: Same NullPointerException protection
- Consistency: Same API as
NullSafe<T>but optimized for primitives
- Java 11 or higher
- Maven 3.6+ or Gradle 6+
# Clone the repository
git clone https://github.com/yasmramos/nullsafe.git
cd nullsafe
# Build with Java 11 compatibility
mvn clean compile test
# Or with Gradle
./gradlew build<dependency>
<groupId>com.github.yasmramos</groupId>
<artifactId>nullsafe</artifactId>
<version>1.0.0</version>
</dependency>implementation 'com.github.yasmramos:nullsafe:1.0.0'All functions are covered by unit tests using JUnit 5. You can run them like this:
mvn testOr if you use Gradle:
gradle testSupports coverage analysis with JaCoCo:
mvn clean test jacoco:reportThe report is generated in:
target/site/jacoco/index.html
We are open to contributions! If you want to improve the library, fix errors, add new functions or translate documentation, go ahead!
- Open an issue
- Fork the repository
- Create a new branch (git checkout -b feature/foo)
- Commit your changes (git commit -m 'Add some foo')
- Push the changes (git push origin feature/foo)
- Create a pull request
This project is under the MIT License.
Β© 2025 yasmramos / Java Community.
If you have questions, suggestions or want to collaborate:
π§ Email: yasmramos95@gmail.com
π GitHub: @yasmramos