This question already has answers here:
Return value from Optional [closed]
(1 answer)
Java Optional if object is not null - returns the method result, if null - returns default value
(6 answers)
Closed 4 years ago.
I often find myself using this idiom:
AtomicReference<MyCoolObject> coolReference = new AtomicReference(new MyCoolObject());
getOptionalValue().ifPresent(presentValue -> {
coolReference.set(new MyCoolObject(presentValue));
});
return coolReference.get();
Is this a bad habit, or a legitimate use of AtomicReference?
Related
This question already has answers here:
Filter values only if not null using lambda in Java8
(6 answers)
Filter null values after map in Java 8 [duplicate]
(1 answer)
Closed 6 months ago.
Let's say I have a Java Stream that contains null values.
How do you remove them ?
Here's a few ways I can think of:
stream.filter(x -> x != null).
stream.filter(Objects::nonNull)
This question already has answers here:
How to check type of variable in Java?
(16 answers)
What is the 'instanceof' operator used for in Java?
(18 answers)
Closed 1 year ago.
I want check the variable type. How do I do that? For e.g
if (num is of String type )
{This must be executed}
I'm currently using Java 17. Any suggestions?
You can use instanceof String to check whether a variable is a String.
if (num instanceof String) {
// code to be executed
}
This question already has answers here:
Idiomatic way to create a Stream from a Nullable object
(7 answers)
Closed 4 years ago.
The following code gives me a NullPointerException. As my examine, it is caused by containerModels being null.
List<DoseDetailMutableDTOToBaseDoseDetailAdapter> adapters =
containerModels.stream()
.map(DoseDetailMutableDTOToBaseDoseDetailAdapter::new)
.collect(Collectors.toList());
How to fix it using java 8?
This could do the trick:
Optional.ofNullable(containerModels)
.orElse(Collections.emptyList())
.stream()
...
This question already has answers here:
Is conversion to String using ("" + <int value>) bad practice?
(8 answers)
Closed 4 years ago.
I'm trying to make sense of some old code.
customerDao.queryForId("" + account.getId);
Is there a reason to do this?
This is done to convert getID into a String. It cannot throw a NullPointerException as calling getID.toString() could if getId is null.
This question already has answers here:
What is the ellipsis (...) for in this method signature?
(5 answers)
What do 3 dots next to a parameter type mean in Java?
(9 answers)
Closed 5 years ago.
I'm looking at the Files class in java 7, and I see this method
copy(InputStream, Path, CopyOptions...)
How do I read "CopyOptions...". What's the ... mean?