import java.util.Date;
import java.util.List;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class GuavaExamples {
public static void main(String[] args) {
/**
* Fail-fast - if you are absolutely convinced an collection contains only
* one element in a particular case, why not test that assumption and catch
* bugs sooner? getOnlyElement will throw a RuntimeException if you pass
* it a collection with zero, or greater than 1, elements.
*/
List<String> iAmDarnSureTheresOnlyGoingToBeOne = Lists.newArrayList("One", "Two");
int lengthOfOnlyString = Iterables.getOnlyElement(iAmDarnSureTheresOnlyGoingToBeOne).length();
/**
* More expressive than names.get(names.length() - 1) and will throw
* better exception if the list is empty
*/
List<String> names = Lists.newArrayList("Bob", "Larry");
Iterables.getLast(names);
/**
* Preconditions allows you to fail-fast without too much ceremony.
* I especially like:
* 1. The optional second argument for crafting the error message
* 2. Upon success, the value you passed in is returned so you can
* chain together method calls - note how we call length only when
* msg != null
*/
String msg = null;
int messageLength = Preconditions.checkNotNull(msg, "Message cannot be null!").length();
/**
* Really useful for writing your own hashCode methods.
*
* Alternatives:
* 1. Write your own buggy version
* 2. Have eclipse generate a huge ugly method for you
*/
int hashCode = Objects.hashCode("xyzzy", 3.14f, new Date());
/**
* Avoid nullStr.equals("yellow")
*/
String maybeNullStr1 = null;
String maybeNullStr2 = "not null yay!"
boolean eq = Objects.equal(nullStr, "maybeNullStr2);
}
}