I have a object from the following class,
public class Customer {
private String email;
private String name;
}
How can I check whether every attribute is not null using Optional from java 8? Or there is another less verbose way?
With out reflection you can't check all in one shot (as others mentioned, Optional not meant for that purpose). But if you are okay to pass all attributes
boolean match = Stream.of(email, name).allMatch(Objects::isNull);
You can have it as an util method inside your Class and use it.
Optional
. OP will need to clarify.
How can I check whether every attribute is not null using Optional from java 8?
Optional is NOT meant for checking nulls. Rather it is intended to act as a container on your objects / fields and provide a null safe reference. The idea is to relieve programmer from checking null references for every field in a sequence of operations covering multiple fields. What you are asking for is exactly opposite of what Optional is supposed to help with.
Here is a good article explaining the purpose of Optional
.
Optional
should be used here? Do you want answers to be restricted to the use ofOptional
or do you accept different answers too?Optional
does. It's a type like any other, so you need to use it as the type of your variables to garner its benefits.Optional
. It explains when to use it and when to not use it. Maybe it helps you too.