添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams
Closed 5 years ago .

The community reviewed whether to reopen this question last year and left it closed:

Original close reason(s) were not resolved

Voting to reopen as not a duplicate. This question is "Does x exist" the other question is "Since x doesn't exist how do I get y". jmoreno Jul 17, 2015 at 23:02 On Java8+ has Optional class in jdk. Example of usage Optional.ofNullable(x).orElse(-1). Other good usage of usage Optional is method map. Let say there object a which is equivalent of json object: "a": {"b":{"c":1}}. To read c value can be such construction like: Optional.ofNullable(a).map(a->a.b).map(b->b.c).orElse(-1). Is much ugly literal syntax than C#, but it is better option that using cascading operator ?: kikea Mar 13, 2019 at 19:46 Another one for my C# vs. Java list. Can't believe there's not even an Objects.coalesce(...) or equivalent. Josh M. Jan 30, 2022 at 17:29 @JoshM. There is indeed a coalesce equivalent from Java 9 onwards. Objects.requireNonNullElse and if you want short-circuiting behaviour there's Objects.requireNonNullElseGet k314159 Apr 6, 2022 at 9:55 @k314159 thank you. I looked at the API quickly and am sad to see that the defaultObj must be non-null. Also sad that it's named require... because it makes it sound like it's going to throw if the parameter is null, in reality it just returns the default object passed in. Poor naming. Should have been coalesce or similar. Josh M. May 7, 2022 at 18:56 Which of course only works if x is an Integer because an int cannot be compared to null . musiKk Mar 7, 2011 at 17:38 @musiKk: and the C# equivalent would only work on int? (or rather any reference type or nullable) jmoreno Jul 17, 2015 at 23:08 @musiKk: type? is how you declare a variable of a nullable type. The c# null coalescing operator only works on nullable or reference types. If the above example was C#, x would be of type int? -- but better written using the null coalescing operator as y=x?? -1; jmoreno Jul 18, 2015 at 15:17 That's what code blocks are for so you can tell that int? is a data type, not a question. :) ErikE Sep 16, 2018 at 2:09

Guava has a method that does something similar called MoreObjects.firstNonNull(T,T) .

Integer x = ...
int y = MoreObjects.firstNonNull(x, -1);

This is more helpful when you have something like

int y = firstNonNull(calculateNullableValue(), -1);

since it saves you from either calling the potentially expensive method twice or declaring a local variable in your code to reference twice.

Unfortunately this will throw a NullPointerException if all values are null. While coalesce can return null. – Stefan Jan 25, 2014 at 18:00 @Stefan: True, though I did say it was "similar" not exactly the same. And this sort of thing is by far the most useful for (and the most used for) cases where you want a fixed, non-null default if something is null. Given that, firstNonNull fails if the second argument is null to help programmer errors be caught faster. – ColinD Jan 27, 2014 at 18:37 The real issue with a solution like this is that it sacrifices the null coalesces lazy evaluation. Since all of the values have to be passed to Objects.firstNonNull, any functions you have passed will be evaluated. This makes it potentially far more computationally expensive than C#'s ??. – Andrew Coonce Oct 27, 2014 at 17:30 @AndrewCoonce: Sure, but there are a lot of use cases (like this example) where you just want a default or something that isn't expensive to compute. And when the alternative is expensive to compute, there's always the ternary. – ColinD Oct 27, 2014 at 17:39

Short answer: no

The best you can do is to create a static utility method (so that it can be imported using import static syntax)

public static <T> T coalesce(T one, T two)
    return one != null ? one : two;

The above is equivalent to Guava's method firstNonNull by @ColinD, but that can be extended more in general

public static <T> T coalesce(T... params)
    for (T param : params)
        if (param != null)
            return param;
    return null;
                I love this! It cleans up so much of my code with annoying nested ternaries or drawn out if-else statements for assignments!
– baohouse
                Oct 9, 2021 at 19:02