I was wondering if there is a way to make the first two lines of the following code a one-liner in Java, so that object
is declared, assigned and null checked in one line:
Object object;
if ((object = queue.poll()) != null) {
// do something with object
}
CodePudding user response:
If you don't mind having the scope of the object variable being confined to the code in the curly brackets, then you can do this:
for (Object object; (object = queue.poll()) != null;) {
// do whatever with object
break;
}
that one isn't too far off from the typical thing we do when reading a file, like this:
for (String line; (line = reader.readLine()) != null;) {
// do something with line
}
or alternatively as suggested by rzwitserloot:
for (Object object = queue.poll; object != null; object = null) {
// do something with object
}
that way it polls only once, and omitting a break in the body of the loop does no harm. Nulling out the object in the increment makes sure the loop terminates after the first pass.
It is kind of abusive having a for loop where you have no intention of looping. I would stay with the multi-line version you started with.
But if you are polling, usually you need a loop anyway.
CodePudding user response:
May not too nice looking:
Optional.ofNullable(queue.poll())
.ifPresent(object -> ... do something with object ...);
Or
Optional.ofNullable(queue.poll()).ifPresent(object -> {
... do something with object ...;
});
So you might have a better opinion of the straight:
Object object = queue.poll();
if (object != null) {
// do something with object
}
CodePudding user response:
The condition is slightly contrived. Therefore, it's hard to meet the requirement without misusing something, like hiding a null
-check with optional, which isn't intended for that purpose.
Actually, the following code will be both the most simple and expressive:
Object object = queue.poll()
if (object != null) {
// do something with object
}
Elimination of a single line will have a cost - the readability of code.
The approach I came up with is to use Stream.ofNullable()
which will produce an empty stream if the provided argument is null
. Then turn the stream into an iterator and invoke forEachRemaining()
on it. This method expects a Supplier
, and you can define it on the spot by placing the logic from the if
-statement, or separately.
Stream.ofNullable(queue.poll()).iterator().forEachRemaining(System.out::println);
Note: forEach()
method defined by the Stream
interface isn't used here deliberately in order to be aligned with the guidelines of the Stream API documentation in regard to side-effects. And an Iterator
is being used instead because there's no such requirements for its method forEachRemaining()
.
CodePudding user response:
Turn your poll()
into a supplier and pretend you're working in a language that encourages monkey patching
Supplier<Optional<Object>> spout = () -> Optional.ofNullable(queue.poll());
spout.get().ifPresent(o -> System.out.println(o));