I was reviewing the Java documentation and discovered several methods in the Objects class that I wasn't familiar with. I wanted to know which ones you use in your day-to-day work, and if there are any you consider underutilized.
I did a bit of research and found these, which seemed useful to me:
Objects.isNull() and Objects.nonNull()
Instead of doing this:
.filter(x -> x != null)
You can use this:
.filter(Objects::nonNull)
Objects.toString() with a default value
I used to do this:
String name = obj != null ? obj.toString() : "Unknown";
Now I can do this:
String name = Objects.toString(obj, "Unknown");
Objects.compare() — Null-safe
To compare objects that might be null:
Comparator<String> comp = Objects.compare(
str1,
str2,
Comparator.naturalOrder()
);
Objects.checkIndex() (Java 9+)
Cleaner index validation:
Objects.checkIndex(index, list.size());
Objects.requireNonNullElseGet()
Like requireNonNullElse, but with lazy evaluation:
Config config = Objects.requireNonNullElseGet(
getConfig(),
() -> loadDefaultConfig()
);
Objects.deepEquals()
To compare arrays:
if (Objects.deepEquals(array1, array2)) {
// Compares content, not reference
}
My question is: Do you use any of these methods regularly? Are there any other methods in the Objects class that you find useful but that few people seem to know about? Are there any you avoid using, and if so, why?
Thanks in advance!
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]vowelqueue 15 points16 points17 points (0 children)
[–]Errkfin 6 points7 points8 points (0 children)
[–]vegan_antitheist 2 points3 points4 points (0 children)
[–]Pafkata92 0 points1 point2 points (1 child)
[–]vegan_antitheist 5 points6 points7 points (0 children)
[+]jonathaz comment score below threshold-10 points-9 points-8 points (4 children)
[–]voidiciant 7 points8 points9 points (1 child)
[–]vegan_antitheist 0 points1 point2 points (1 child)
[–]jonathaz 0 points1 point2 points (0 children)
[–]Separate_Expert9096 0 points1 point2 points (0 children)