how to rewrite this function to be more Java 8 with Optionals? Or should I just leave it as it is?
public void setMemory(ArrayList<Integer> memory) {
if (memory == null)
throw new IllegalArgumentException("ERROR: memory object can't be null.");
if (memory.contains(null))
throw new IllegalArgumentException("ERROR: memory object can't contain null value.");
this.memory = memory;
}
Java Check if Object Is Null Using java. Objects class has static utility methods for operating an object. One of the methods is isNull() , which returns a boolean value if the provided reference is null, otherwise it returns false. We have created two classes - User1 and User2 as shown in the code below.
In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.
Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .
Java 8 Example: Filter null values from a stream We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a stream.
For the first case I would use:
Objects.requireNonNull()
.
I don't think Optional
is a way to go here as null
is an illegal value.
You've got a pattern condition -> throw an exception
which can be moved to a method:
private void checkOrElseThrow(boolean condition, Supplier<? extends RuntimeException> exceptionSupplier) {
if (condition) {
throw exceptionSupplier.get();
}
}
public void setMemory(List<Integer> memory) {
checkOrElseThrow(memory == null, () -> new IllegalArgumentException("message #1"));
checkOrElseThrow(memory.contains(null), () -> new IllegalArgumentException("message #2"));
this.memory = memory;
}
If the type of the exception is not going to be changed, it's reasonable to pass only the message of the exception (thank @tobias_k for pointing it out):
private void checkOrElseThrow(boolean condition, String exceptionMessage) {
if (condition) {
throw new IllegalArgumentException(exceptionMessage);
}
}
public void setMemory(List<Integer> memory) {
checkOrElseThrow(memory == null, "message #1");
checkOrElseThrow(memory.contains(null), "message #2");
this.memory = memory;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With