Ankur Saran Ankur Saran - 3 months ago 16
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 = (rest.host != 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

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

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.host, 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.host, rest.payload, rest.lockQueue, rest.endpoint).stream().allMatch(Objects::nonNull)
Comments