-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?

Rogerio Camorim
  • 331
  • 1
  • 4
  • 14
  • 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 Mar 17 '18 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. – Silvio Mayolo Mar 17 '18 at 16:32
  • I always recommend watching [this talk](https://www.youtube.com/watch?v=Ej0sss6cq14) (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 Mar 17 '18 at 16:35
  • Possible duplicate of [What is the best way to know if all the variables in a Class are null?](https://stackoverflow.com/questions/12362212/what-is-the-best-way-to-know-if-all-the-variables-in-a-class-are-null) – Ousmane D. Mar 17 '18 at 17:14
  • if for some reason you're insisting on a java-8 solution then there is also an answer here --> https://stackoverflow.com/questions/12362212/what-is-the-best-way-to-know-if-all-the-variables-in-a-class-are-null/40238927#40238927 – Ousmane D. Mar 17 '18 at 17:15
  • It is not a Optional restrict. If there's any other way less verbose it can do. – Rogerio Camorim Mar 18 '18 at 10:49
  • Don't understand people that put negatives value in a simple question. – Rogerio Camorim Mar 18 '18 at 10:50

2 Answers2

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Just as a note, this answer does not answer the question **if** OP only wants solutions using `Optional`. OP will need to clarify. – Zabuzard Mar 17 '18 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.

VHS
  • 9,534
  • 3
  • 19
  • 43