Ankur Saran Ankur Saran - 1 year ago 215
Java Question

Java Multiple comparision in java

Pardon me if this is a stupid question.. I was wondering if there is any support for following comparison in Java:

(a, b, c .... != null)
in place for :

(a != null && b != null && c != null && d ! null and so on ..)

I was trying to make code more readable as my code which is almost unreadable due to multiple condition in single statement.

code :

variable = ( != null && rest.payload != null
&& rest.lockQueue != null && rest.endpoint != null ) || rest.default.setState
|| rest.scheduler.locked && rest.scheduler.queue.isFull()
&& lastPayload.getActivity.status.executing ? onExecute(rest.payload) : wait(TIME);

Answer Source

If your elements are in a collection, use -> x != null). Actually, there's even a predicate for that:

If your elements aren't in a collection, you can still use Arrays.asList() to create an ad-hoc list from them. So, in your case:

Arrays.asList(, rest.payload, rest.lockQueue, rest.endpoint).stream().allMatch(Objects::nonNull)

EDIT: actually, as someone mentioned in another answer, there is a method that creates a stream directly, namely Stream.of(...). So:

Stream.of(, rest.payload, rest.lockQueue, rest.endpoint).stream().allMatch(Objects::nonNull)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download