-3

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?

7
  • Why do you think Optional should be used here? Do you want answers to be restricted to the use of Optional or do you accept different answers too?
    – Zabuzard
    Commented Mar 17, 2018 at 16:31
  • I think you're misunderstanding what 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. Commented Mar 17, 2018 at 16:32
  • I always recommend watching this talk (by one of the designers) to people that misunderstood Optional. It explains when to use it and when to not use it. Maybe it helps you too.
    – Zabuzard
    Commented Mar 17, 2018 at 16:35
  • Possible duplicate of What is the best way to know if all the variables in a Class are null?
    – Ousmane D.
    Commented Mar 17, 2018 at 17:14
  • if for some reason you're insisting on a java-8 solution then there is also an answer here --> stackoverflow.com/questions/12362212/…
    – Ousmane D.
    Commented Mar 17, 2018 at 17:15

2 Answers 2

3

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.

1
  • Just as a note, this answer does not answer the question if OP only wants solutions using Optional. OP will need to clarify.
    – Zabuzard
    Commented Mar 17, 2018 at 16:33
1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.