Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1.  
  2. import java.util.Date;
  3. import java.util.List;
  4.  
  5. import com.google.common.base.Objects;
  6. import com.google.common.base.Preconditions;
  7. import com.google.common.collect.Iterables;
  8. import com.google.common.collect.Lists;
  9.  
  10. public class GuavaExamples {
  11.   public static void main(String[] args) {
  12.     /**
  13.      * Fail-fast - if you are absolutely convinced an collection contains only
  14.      * one element in a particular case, why not test that assumption and catch
  15.      * bugs sooner?  getOnlyElement will throw a RuntimeException if you pass
  16.      * it a collection with zero, or greater than 1, elements.
  17.      */
  18.     List<String> iAmDarnSureTheresOnlyGoingToBeOne = Lists.newArrayList("One", "Two");
  19.     int lengthOfOnlyString = Iterables.getOnlyElement(iAmDarnSureTheresOnlyGoingToBeOne).length();
  20.    
  21.     /**
  22.      * More expressive than names.get(names.length() - 1) and will throw
  23.      * better exception if the list is empty
  24.      */
  25.     List<String> names = Lists.newArrayList("Bob", "Larry");
  26.     Iterables.getLast(names);
  27.    
  28.     /**
  29.      * Preconditions allows you to fail-fast without too much ceremony.
  30.      * I especially like:
  31.      * 1. The optional second argument for crafting the error message
  32.      * 2. Upon success, the value you passed in is returned so you can
  33.      * chain together method calls - note how we call length only when
  34.      * msg != null
  35.      */
  36.     String msg = null;
  37.     int messageLength = Preconditions.checkNotNull(msg, "Message cannot be null!").length();
  38.  
  39.     /**
  40.      * Really useful for writing your own hashCode methods.
  41.      *
  42.      * Alternatives:
  43.      * 1. Write your own buggy version
  44.      * 2. Have eclipse generate a huge ugly method for you
  45.      */
  46.     int hashCode = Objects.hashCode("xyzzy", 3.14f, new Date());
  47.    
  48.     /**
  49.      * Avoid nullStr.equals("yellow")
  50.      */
  51.     String maybeNullStr1 = null;
  52.     String maybeNullStr2 = "not null yay!"
  53.     boolean eq = Objects.equal(nullStr, "maybeNullStr2);
  54.  }
  55. }