Class MoreObjects

    • Method Detail

      • firstNonNull

        public static <T> T firstNonNull​(@CheckForNull
                                         T first,
                                         T second)
        Returns the first of two given parameters that is not null, if either is, or otherwise throws a NullPointerException.

        To find the first non-null element in an iterable, use Iterables.find(iterable, Predicates.notNull()). For varargs, use Iterables.find(Arrays.asList(a, b, c, ...), Predicates.notNull()), static importing as necessary.

        Note: if first is represented as an Optional, this can be accomplished with first.or(second). That approach also allows for lazy evaluation of the fallback instance, using first.or(supplier).

        Java 9 users: use java.util.Objects.requireNonNullElse(first, second) instead.

        Returns:
        first if it is non-null; otherwise second if it is non-null
        Throws:
        NullPointerException - if both first and second are null
        Since:
        18.0 (since 3.0 as Objects.firstNonNull()).
      • toStringHelper

        public static MoreObjects.ToStringHelper toStringHelper​(Object self)
        Creates an instance of MoreObjects.ToStringHelper.

        This is helpful for implementing Object.toString(). Specification by example:

        
         // Returns "ClassName{}"
         MoreObjects.toStringHelper(this)
             .toString();
        
         // Returns "ClassName{x=1}"
         MoreObjects.toStringHelper(this)
             .add("x", 1)
             .toString();
        
         // Returns "MyObject{x=1}"
         MoreObjects.toStringHelper("MyObject")
             .add("x", 1)
             .toString();
        
         // Returns "ClassName{x=1, y=foo}"
         MoreObjects.toStringHelper(this)
             .add("x", 1)
             .add("y", "foo")
             .toString();
        
         // Returns "ClassName{x=1}"
         MoreObjects.toStringHelper(this)
             .omitNullValues()
             .add("x", 1)
             .add("y", null)
             .toString();
         

        Note that in GWT, class names are often obfuscated.

        Parameters:
        self - the object to generate the string for (typically this), used only for its class name
        Since:
        18.0 (since 2.0 as Objects.toStringHelper()).