<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>23.0</version> </dependency>
The Optional class
enables the parameter to have an empty operation when it is defined, so there is no need to wait until the method runs to the empty exception.
public class GuavaTester { public static void main(String args[]){ GuavaTester guavaTester = new GuavaTester(); Integer invalidInput = null; Optional<Integer> a = Optional.of(invalidInput);//Empty exception has been thrown here Optional<Integer> b = Optional.of(new Integer(10)); System.out.println(guavaTester.sum(a,b)); } public Integer sum(Optional<Integer> a, Optional<Integer> b){ return a.get() + b.get(); //get the value } }
Generally use of, get, fromNullable, or
Preconditions classes
generally use
static int checkElementIndex(int index, int size)
to ensure that the index specifies a valid element of an array, list or size string.
static int checkElementIndex(int index, int size, String desc)
ensures that the index specifies a valid element of an array, list, or size-sized string.
static <T> T checkNotNull(T reference, Object errorMessage)
ensures that the object reference passed as a parameter to the calling method is not null.
static int checkPositionIndex(int index, int size)
ensures that the index specifies a valid position in an array, list, or size-sized string.
static int checkPositionIndex(int index, int size, String desc)
ensures that the index specifies a valid position for an array, list, or size-sized string.
String desc //For the information displayed when an error occurs
Ordering class //The
Objects class
used for sorting static boolean equal(Object a, Object b)
determines whether two objects that may be empty are equal.
Bimap interface
public class GuavaTester { public static void main(String args[]){ BiMap<Integer, String> empIDNameMap = HashBiMap.create(); empIDNameMap.put(new Integer(101), "Mahesh"); empIDNameMap.put(new Integer(102), "Sohan"); empIDNameMap.put(new Integer(103), "Ramesh"); //Emp Id of Employee "Mahesh" System.out.println(empIDNameMap.inverse().get("Mahesh")); } }
Objects.equal can realize the comparison of null
objectsComparisonChain (sorting comparison is simpler)
sorter[Ordering]
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(); }
hashCode:
Guava's Objects.hashCode(Object...) will calculate a reasonable, order-sensitive hash value for the incoming field sequence.
Immutable collection ()
cache
String processing
Range
I/O
byte stream and character stream
Guava provides a very lightweight implementation of EventBus in the process, which can well realize the decoupling between modules.