My technical blog is often maliciously crawled and reproduced by rogue websites. Please move to the original article: Workshop.
Null
Guava uses optional to indicate T-type references that may be null.
Create:Optional. Of (t) does not accept nullOptional. fromnullable (t) accepts nullOptional. Absent ()
Query:Ispresent ()Get ()Or (t) if it is null, It is tOrnull ()
Others:Objects. firstnonnull (t, t) is used to specify the default value for null. If both are null, nullpointerexception is thrown.
Emptytonull (string ),Nulltoempty (string)
Prerequisites
Usage:
checkArgument(i >= 0, "Argument was %s but expected nonnegative", i);checkArgument(i < j, "Expected i < j, but %s > %s", i, j);
Checkargument (Boolean)Checknotnull (t)Checkstate (Boolean)
Checkelementindex (INT index, int size)Checkpositionindexes (INT start, int end, int size)
Inline use:This. Field = checknotnull (field)
Object Method
Objects. Equals (a, B) equals that can be nullObjects. Hash (object ...)
Tostring ():
// Returns "ClassName{x=1}"Objects.toStringHelper(this).add("x", 1).toString();// Returns "MyObject{x=1}"Objects.toStringHelper("MyObject").add("x", 1).toString();
Compare ():
public int compareTo(Foo that) { return ComparisonChain.start() .compare(this.aString, that.aString) .compare(this.anInt, that.anInt) .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast()) .result();}Sort
Ordering: comparator implementation
Structure: natural order of natural ()Usingtostring () Lexicographic OrderFrom (comparator)
Chain call:Reverse reverse ()Nullsfirst ()Nullslast ()Lexicographical ()Onresultof (function)
Ordering<Foo> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<Foo, String>() { public String apply(Foo foo) { return foo.sortedBy; }});
Set and element:Greatestof (iterable, int K)Min (iterable)Min (E, E ...)
Isordered (iterable)Sortedcopy (iterable)