Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Google Guava - Core libraries for Java & Android

Google Guava - Core libraries for Java & Android

Talk at GDG DevFest Barcelona 2013.

The Guava project contains several of Google's core libraries that we rely on in our Java-based projects: collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, and so forth.

Jordi Gerona

October 11, 2013
Tweet

Other Decks in Technology

Transcript

  1. map = {Foo: bar, null, Baz: qux} map.get(“Foo”); map.get(“quux”); //

    returns null map.get(null); // returns null Basics: Avoid using null
  2. map = {Foo: bar, null, Baz: qux} map.get(“Foo”); map.get(“quux”); //

    returns null map.get(null); // returns null // Null to indicate absence // vs null value Basics: Avoid using null
  3. if (seats <= 0) { throw new IllegalArgumentException(“Seats must be

    positive, but was ” + seats); } Basics: Preconditions
  4. if (seats <= 0) { throw new IllegalArgumentException(“Seats must be

    positive, but was ” + seats); } checkArgument(seats > 0, “Seats must be positive, but was %s”, seats); Basics: Preconditions
  5. // Always use static import import static com.google.common.base.Preconditions.checkArgument; checkArgument(seats >

    0, “Seats must be positive, but was %s”, seats); Basics: Preconditions
  6. import static com.google.common.base.Preconditions.checkArgument; // Check what you expect to be

    true checkArgument(seats > 0, “Seats must be positive, but was %s”, seats); Basics: Preconditions
  7. import static com.google.common.base.Preconditions.checkArgument; // “%s” specifier is recognized as a

    placeholder in // these messages (the only one) checkArgument(seats > 0, “Seats must be positive, but was %s”, seats); Basics: Preconditions
  8. void execute(Job job) { checkNotNull(job, “Job can’t be null”); //

    serious business } // checkNotNull() throws NullPointerException Basics: Preconditions
  9. void execute(Job job) { checkNotNull(job, “Job can’t be null”); checkArgument(!job.started(),

    “Job already started”); // serious business } // checkArgument() throws IllegalArgumentException // checkNotNull() throws NullPointerException Basics: Preconditions
  10. void execute(Job job) { checkNotNull(job, “Job can’t be null”); checkArgument(!job.started(),

    “Job already started”); // serious business checkState(seatsAvailabe <= totalSeats, “You’ve sold more seats than available! This should never happen. %s/%s”, seatsAvailable, totalSeats); } // checkState() throws IllegalStateException // checkArgument() throws IllegalArgumentException // checkNotNull() throws NullPointerException Basics: Preconditions
  11. this.foo = checkNotNull(foo); // list, string or array checks checkElementIndex(index,

    size); checkPositionIndex(index, size); checkPositionIndexes(start, end, size); Goodies! javadoc
  12. @Override public boolean equals(Object obj) { if (obj == this)

    { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } Person guest = (Person) obj; return id == guest.id && (firstName == guest.firstName || (firstName != null && firstName.equals(guest.getFirstName()))) && (lastName == guest.lastName || (lastName != null && lastName.equals(guest.getLastName()))); } Basics: Objects
  13. @Override public boolean equals(Object obj) { if (obj == this)

    { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } Person guest = (Person) obj; return id == guest.id && (firstName == guest.firstName || (firstName != null && firstName.equals(guest.getFirstName()))) && (lastName == guest.lastName || (lastName != null && lastName.equals(guest.getLastName()))); } Basics: Objects F
  14. @Override public boolean equals(Object obj) { if (obj == this)

    { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } Person guest = (Person) obj; return id == guest.id && (firstName == guest.firstName || (firstName != null && firstName.equals(guest.getFirstName()))) && (lastName == guest.lastName || (lastName != null && lastName.equals(guest.getLastName()))); } Basics: Objects FM
  15. @Override public boolean equals(Object obj) { if (obj == this)

    { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } Person guest = (Person) obj; return id == guest.id && (firstName == guest.firstName || (firstName != null && firstName.equals(guest.getFirstName()))) && (lastName == guest.lastName || (lastName != null && lastName.equals(guest.getLastName()))); } Basics: Objects FML
  16. @Override public boolean equals(Object obj) { if (obj instanceof Person)

    { Person that = (Person) obj; return Objects.equal(firstName, that.firstName) && Objects.equal(lastName, that.lastName); } else { return false; } } Basics: Objects
  17. @Override public boolean equals(Object obj) { if (obj instanceof Person)

    { Person that = (Person) obj; return Objects.equal(firstName, that.firstName) // null safe! && Objects.equal(lastName, that.lastName); // null safe x2! } else { return false; } } Basics: Objects
  18. @Override public boolean equals(Object obj) { if (obj instanceof Person)

    { Person that = (Person) obj; return Objects.equal(firstName, that.firstName) && Objects.equal(lastName, that.lastName); } else { return false; } } // JDK 1.7 introduced equivalent Objects.equals() method. Basics: Objects
  19. @Override public int hashCode() { final int prime = 31;

    int result = 1; result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + id; result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); return result; } Basics: Objects
  20. @Override public int hashCode() { final int prime = 31;

    int result = 1; result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + id; result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); return result; } // oh, grumpy cat! Basics: Objects
  21. @Override public int hashCode() { // sensible, order-sensitive hash return

    Objects.hashCode(firstName, lastName); } Basics: Objects
  22. @Override public int hashCode() { return Objects.hashCode(firstName, lastName); } //

    JDK 1.7 introduced equivalent Objects.hash() method. Basics: Objects
  23. @Override public String toString() { return Objects.toStringHelper(this) .add("firstName", firstName) .add("lastName",

    lastName) .add("catName", catName) .toString(); } // returns Person{firstName=Solid, lastName=Snake, catName=null} Basics: Objects
  24. @Override public String toString() { return Objects.toStringHelper(this) .add("firstName", firstName) .add("lastName",

    lastName) .add("catName", catName) .omitNullValues() .toString(); } Basics: Objects
  25. @Override public String toString() { return Objects.toStringHelper(this) .add("firstName", firstName) .add("lastName",

    lastName) .add("catName", catName) .omitNullValues() .toString(); } // returns Person{firstName=Solid, lastName=Snake} Basics: Objects
  26. Comparator<Person> byDescAgeName = new Comparator<Person>() { public int compare(Person p1,

    Person p2) { int result = p2.getAge() - p1.getAge(); // ugh! return (result == 0) ? p1.compareTo(p2) : result; } }; // Ok, it’s not that bad -- But it’s pretty hard to get Basics: Ordering
  27. Comparator<Person> byDescAgeName = new Comparator<Person>() { public int compare(Person p1,

    Person p2) { int result = p2.getAge() - p1.getAge(); // ugh! return (result == 0) ? p1.compareTo(p2) : result; } }; // Ok, it’s not that bad -- But it’s pretty hard to get // We’re lucky ints and Person are Comparable, otherwise you’ll // have to implement it Basics: Ordering
  28. Comparator<Person> byDescAgeName = new Comparator<Person>() { public int compare(Person p1,

    Person p2) { return ComparisonChain.start() .compare(p2.getAge(), p1.getAge()) .compare(p1, p2) .result(); } }; Basics: Ordering
  29. Comparator<Person> byDescAgeName = new Comparator<Person>() { public int compare(Person p1,

    Person p2) { return ComparisonChain.start() .compare(p2.getAge(), p1.getAge()) .compare(p1, p2) .result(); } }; // Short-circuits: If one comparison is not equals, stop and return Basics: Ordering
  30. Comparator<Person> byDescAgeName = Ordering.natural() .reverse() .onResultOf(new Function<Person, Integer>() { public

    Integer apply(Person person) { return person.getAge(); }}) .compound(Ordering.natural()); } }; Basics: Ordering
  31. Comparator<Person> byDescAgeName = Ordering.natural() .reverse() .onResultOf(new Function<Person, Integer>() { public

    Integer apply(Person person) { return person.getAge(); }}) .compound(Ordering.natural()); } }; // Read backwards Basics: Ordering
  32. Ordering is an “enriched” Comparator. It’s fluent. // Subclass Ordering

    and implement compare(T,T) Ordering<Throwable> ORDER_BY_CLASS_NAME = (left, right) -> { return Ordering.usingToString() .compare(left.getClass(), right.getClass()); }; Goodies! javadoc
  33. Ordering is an “enriched” Comparator. It’s fluent. // Subclass Ordering

    and implement compare(T,T) Ordering<Throwable> ORDER_BY_CLASS_NAME = (left, right) -> { return Ordering.usingToString() .compare(left.getClass(), right.getClass()); }; // Or create one Ordering.from(comparator); Ordering.natural(); Goodies! javadoc
  34. Ordering is an “enriched” Comparator. It’s fluent. // Subclass Ordering

    and implement compare(T,T) Ordering<Throwable> ORDER_BY_CLASS_NAME = (left, right) -> { return Ordering.usingToString() .compare(left.getClass(), right.getClass()); }; // Or create one Ordering.from(comparator); Ordering.natural(); // And chain! ORDER_BY_CLASS_NAME.nullsFirst().reverse().compound(comparator); Goodies! javadoc
  35. void oneLineOfCode() { DatagramPacket packet = new DatagramPacket(data, length); }

    // Compile error, throws IOException Basics: Throwables
  36. void oneLineOfCode() throws IOException { DatagramPacket packet = new DatagramPacket(data,

    length); } void someLayer() { oneLineOfCode(); } Basics: Throwables
  37. void oneLineOfCode() throws IOException { DatagramPacket packet = new DatagramPacket(data,

    length); } void someLayer() { oneLineOfCode(); } // Compile error, throws IOException Basics: Throwables
  38. void oneLineOfCode() throws IOException { DatagramPacket packet = new DatagramPacket(data,

    length); } void someLayer() throws IOException { oneLineOfCode(); } void someCoolAbstraction() { someLayer(); } Basics: Throwables
  39. void oneLineOfCode() throws IOException { DatagramPacket packet = new DatagramPacket(data,

    length); } void someLayer() throws IOException { oneLineOfCode(); } void someCoolAbstraction() { someLayer(); } // Compile error, AGAIN Basics: Throwables
  40. void oneLineOfCode() throws IOException { DatagramPacket packet = new DatagramPacket(data,

    length); } void someLayer() throws IOException { oneLineOfCode(); } void someCoolAbstraction() throws IOException { someLayer(); } Basics: Throwables
  41. void oneLineOfCode() throws IOException { DatagramPacket packet = new DatagramPacket(data,

    address); } void someLayer() throws IOException { oneLineOfCode(); } void someCoolAbstraction() throws IOException { someLayer(); } // c’mon... Basics: Throwables
  42. void oneLineOfCode() { // Take 2 DatagramPacket packet = new

    DatagramPacket(data, length); } Basics: Throwables
  43. void oneLineOfCode() { try { DatagramPacket packet = new DatagramPacket(data,

    length); } catch (IOException e) { } } Basics: Throwables
  44. void oneLineOfCode() { try { DatagramPacket packet = new DatagramPacket(data,

    length); } catch (IOException e) { // Really? Swallow? Sure? At least explain why! } } Basics: Throwables
  45. void oneLineOfCode() { try { DatagramPacket packet = new DatagramPacket(data,

    length); } catch (IOException e) { SendMeAnEmail.error(); } } Basics: Throwables
  46. void oneLineOfCode() { try { DatagramPacket packet = new DatagramPacket(data,

    length); } catch (IOException e) { SendMeAnEmail.error(); Oh.theLogger().fatal(“WHY Y U FATAL NOW?”); } } Basics: Throwables
  47. void oneLineOfCode() { try { DatagramPacket packet = new DatagramPacket(data,

    length); } catch (IOException e) { SendMeAnEmail.error(); Oh.theLogger().fatal(“WHY Y U FATAL NOW?”); // repeat for every catch block } } Basics: Throwables
  48. void oneLineOfCode() { try { DatagramPacket packet = new DatagramPacket(data,

    length); } catch (IOException e) { SendMeAnEmail.error(); Oh.theLogger().fatal(“WHY Y U FATAL NOW?”); // repeat for every catch block // AGAIN AND AGAIN } } Basics: Throwables
  49. void oneLineOfCode() { try { DatagramPacket packet = new DatagramPacket(data,

    address); } catch (IOException e) { SendMeAnEmail.error(); Oh.theLogger().fatal(“WHY Y U FATAL NOW?”); // repeat for every catch block // AGAIN AND AGAIN } } Basics: Throwables
  50. void oneLineOfCode() { // Take 3 DatagramPacket packet = new

    DatagramPacket(data, length); } Basics: Throwables
  51. void oneLineOfCode() { try { DatagramPacket packet = new DatagramPacket(data,

    length); } catch (IOException e) { handle(e); } } // We know what to do with this Exception, like recover Basics: Throwables
  52. void oneLineOfCode() { try { DatagramPacket packet = new DatagramPacket(data,

    length); } catch (IOException e) { throw new MyException(e); } } // Translate the Exception to another one more suitable Basics: Throwables
  53. void oneLineOfCode() { try { DatagramPacket packet = new DatagramPacket(data,

    length); } catch (IOException e) { throw Throwables.propagate(e); } } // Propagates the throwable as-is if it is a RuntimeException or // an Error, or wraps it in a RuntimeException and throws it // otherwise. Basics: Throwables
  54. // more forms propagateIfInstanceOf(throwable,exceptionClass); propagateIfPossible(throwable); propagateIfPossible(throwable, exceptionClass); General practice: Convert

    checked exceptions to unchecked exceptions Checked exceptions... are a bad idea? Goodies… or gotcha’s! javadoc
  55. // more forms propagateIfInstanceOf(throwable,exceptionClass); propagateIfPossible(throwable); propagateIfPossible(throwable, exceptionClass); General practice: Convert

    checked exceptions to unchecked exceptions Checked exceptions... are a bad idea? Don’t use propagate() to ignore IOExceptions and so on Goodies… or gotcha’s! javadoc
  56. We have String.split bro! “,f,,o, o,”.split(“,”) returns: a. [“”, “f”,

    “”, “o”, “ o”,””] b. [null, “f”, null, “o” ,”o”, null] Strings: Splitter
  57. We have String.split bro! “,f,,o, o,”.split(“,”) returns: a. [“”, “f”,

    “”, “o”, “ o”,””] b. [null, “f”, null, “o” ,”o”, null] c. [“f”, null, “o”, “o”] Strings: Splitter
  58. We have String.split bro! “,f,,o, o,”.split(“,”) returns: a. [“”, “f”,

    “”, “o”, “ o”,””] b. [null, “f”, null, “o” ,”o”, null] c. [“f”, null, “o”, “o”] d. [“f”, ”o”, ”o”] Strings: Splitter
  59. We have String.split bro! “,f,,o, o,”.split(“,”) returns: a. [“”, “f”,

    “”, “o”, “ o”,””] b. [null, “f”, null, “o” ,”o”, null] c. [“f”, null, “o”, “o”] d. [“f”, ”o”, ”o”] e. None of above Strings: Splitter
  60. We have String.split bro! “,f,,o, o,”.split(“,”) returns: a. [“”, “f”,

    “”, “o”, “ o”,””] b. [null, “f”, null, “o” ,”o”, null] c. [“f”, null, “o”, “o”] d. [“f”, ”o”, ”o”] e. None of above Strings: Splitter
  61. We have String.split bro! “,f,,o, o,”.split(“,”) returns: a. [“”, “f”,

    “”, “o”, “ o”,””] b. [null, “f”, null, “o” ,”o”, null] c. [“f”, null, “o”, “o”] d. [“f”, ”o”, ”o”] e. None of above Strings: Splitter
  62. We have String.split bro! “,f,,o, o,”.split(“,”) returns: a. [“”, “f”,

    “”, “o”, “ o”,””] b. [null, “f”, null, “o” ,”o”, null] c. [“f”, null, “o”, “o”] d. [“f”, ”o”, ”o”] e. None of above Returns: [“”, “f”, “”, “o”, “ o”] Strings: Splitter
  63. We have String.split bro! “,f,,o, o,”.split(“,”) returns: a. [“”, “f”,

    “”, “o”, “ o”,””] b. [null, “f”, null, “o” ,”o”, null] c. [“f”, null, “o”, “o”] d. [“f”, ”o”, ”o”] e. None of above Returns: [“”, “f”, “”, “o”, “ o”] Only trailing empty strings are skipped. Strings: Splitter
  64. “,f,,o, o,”.split(“,”) we probably want [“f”,”o”,”o”] Splitter.on(‘,’) .split(“,f,,o, o,”); //

    returns [“”,”f”,””,”o”,” o”,””] // Doesn’t discard trailing separators! Strings: Splitter
  65. “,f,,o, o,”.split(“,”) we probably want [“f”,”o”,”o”] static final Splitter COMMA

    = Splitter.on(‘,’) .omitEmptyStrings() .trimResults() .split(“,f,,o, o,”); // Best practice: declare Splitters as static final Strings: Splitter javadoc
  66. [“Jack, “Chloe”, “Tony”, null, “Nina”, “Logan”] Joiner.on(“, “) .join(twentyFour); //

    throws NullPointerException! // null-hostile operations everywhere, good thing ;) Strings: Joiner
  67. // More matchers CharMatcher.ANY; CharMatcher.BREAKING_WHITESPACE; CharMatcher.WHITESPACE; CharMatcher.INVISIBLE; CharMatcher.DIGIT; // Unicode

    CharMatcher.JAVA_DIGIT; // Java’s definition CharMatcher.is(char); CharMatcher.isNot(char); Goodies! javadoc
  68. // More matchers CharMatcher.ANY; CharMatcher.BREAKING_WHITESPACE; CharMatcher.WHITESPACE; CharMatcher.INVISIBLE; CharMatcher.DIGIT; // Unicode

    CharMatcher.JAVA_DIGIT; // Java’s definition CharMatcher.is(char); CharMatcher.isNot(char); // And operations .replaceFrom(charSequence, replacement); .collapseFrom(charSequence, replacement); .trimFrom(charSequence, replacement); Goodies! javadoc
  69. HtmlEscapers.htmlEscaper().escape("Foo > bar"); XmlEscapers.xmlAttributeEscaper().escape("foo \"bar\""); XmlEscapers.xmlContentEscaper().escape("foo \"bar\""); Escaper myEscaper =

    Escapers.builder() // custom Escaper .addEscape(‘\’’, “‘’”) .addEscape(‘&’, “\&”) .build(); Escapers javadoc
  70. Function<String, Integer> lengthFunction = new Function<String, Integer>() { public Integer

    apply(String string) { return string.length(); } }; Predicate<String> allCaps = new Predicate<String>() { public boolean apply(String string) { return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string); } }; Multiset<Integer> lengths = HashMultiset.create( Iterables.transform(Iterables.filter(strings, allCaps), lengthFunction)); Collections: Functional Idiom
  71. Function<String, Integer> lengthFunction = new Function<String, Integer>() { public Integer

    apply(String string) { return string.length(); } }; Predicate<String> allCaps = new Predicate<String>() { public boolean apply(String string) { return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string); } }; Multiset<Integer> lengths = HashMultiset.create( Iterables.transform(Iterables.filter(strings, allCaps), lengthFunction)); Collections: Functional Idiom
  72. Multiset<Integer> lengths = HashMultiset.create(); for (String string : strings) {

    if (CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string)) { lengths.add(string.length()); } } Collections: Functional Idiom
  73. Multiset<Integer> lengths = HashMultiset.create(); for (String string : strings) {

    if (CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string)) { lengths.add(string.length()); } } // Use Imperative, you’ve already survived! Collections: Functional Idiom
  74. Multiset<Integer> lengths = HashMultiset.create(); for (String string : strings) {

    if (CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string)) { lengths.add(string.length()); } } // Use Imperative, you’ve already survived! // Wait for Java 8! Collections: Functional Idiom explain
  75. Immutable = Thread-safe static final ImmutableSet<String> FOO_NAMES = ImmutableSet.of(“foo”, “bar”,

    “baz”); // ImmutableList, ImmutableMap... Collections: Immutable types
  76. Immutable = Thread-safe static final ImmutableSet<String> FOO_NAMES = ImmutableSet.of(“foo”, “bar”,

    “baz”); ImmutableList<String> defensiveCopy = ImmutableList.copyOf(someList); Collections: Immutable types
  77. Immutable = Thread-safe static final ImmutableSet<String> FOO_NAMES = ImmutableSet.of(“foo”, “bar”,

    “baz”); ImmutableList<String> defensiveCopy = ImmutableList.copyOf(someList); // Prefer Immutable collections over JDK Collections.unmodifiableXX // for efficiency and consistency Collections: Immutable types explain
  78. A bag Just like a Set<E> with repeated values You’ve

    done this with ArrayList<E> or Map<E, Integer> Collections: Multiset<E>
  79. A bag Just like a Set<E> with repeated values You’ve

    done this with ArrayList<E> or Map<E, Integer> Multiset<Person> ppl = HashMultiset.create(); Collections: Multiset<E>
  80. A bag Just like a Set<E> with repeated values You’ve

    done this with ArrayList<E> or Map<E, Integer> Multiset<Person> ppl = HashMultiset.create(); ppl.add(jack); ppl.add(charles); ppl.add(jack); Collections: Multiset<E>
  81. A bag Just like a Set<E> with repeated values You’ve

    done this with ArrayList<E> or Map<E, Integer> Multiset<Person> ppl = HashMultiset.create(); ppl.add(jack); ppl.add(charles); ppl.add(jack); // prints [jack x 2, charles x 1] Collections: Multiset<E>
  82. A bag Just like a Set<E> with repeated values You’ve

    done this with ArrayList<E> or Map<E, Integer> Multiset<Person> ppl = HashMultiset.create(); ppl.add(jack); ppl.add(charles); ppl.add(jack); ppl.count(jack); Collections: Multiset<E>
  83. A bag Just like a Set<E> with repeated values You’ve

    done this with ArrayList<E> or Map<E, Integer> Multiset<Person> ppl = HashMultiset.create(); ppl.add(jack); ppl.add(charles); ppl.add(jack); ppl.count(jack); // returns 2 Collections: Multiset<E>
  84. A bag Just like a Set<E> with repeated values You’ve

    done this with ArrayList<E> or Map<E, Integer> Multiset<Person> ppl = HashMultiset.create(); ppl.add(jack); ppl.add(charles); ppl.add(jack); ppl.count(jack); // Goodies: elementSet(), entrySet(), setCount(E, int)... Collections: Multiset<E> explain
  85. A Map<K, V> with multiple values You’ve done this with

    Map<K, List<V>> Collections: Multimap<K, V>
  86. A Map<K, V> with multiple values You’ve done this with

    Map<K, List<V>> Multimap<Person, Ticket> ticketsByPerson = ArrayListMultimap.create(); Collections: Multimap<K, V>
  87. A Map<K, V> with multiple values You’ve done this with

    Map<K, List<V>> Multimap<Person, Ticket> ticketsByPerson = ArrayListMultimap.create(); ticketsByPerson.put(jack, ctu); ticketsByPerson.put(jack, division); Collections: Multimap<K, V>
  88. A Map<K, V> with multiple values You’ve done this with

    Map<K, List<V>> Multimap<Person, Ticket> ticketsByPerson = ArrayListMultimap.create(); ticketsByPerson.put(jack, ctu); ticketsByPerson.put(jack, division); ticketsByPerson.get(jack); // returns a view of the associated values, a List. // With SetMultimap returns a Set. Collections: Multimap<K, V>
  89. A Map<K, V> with multiple values You’ve done this with

    Map<K, List<V>> Multimap<Person, Ticket> ticketsByPerson = ArrayListMultimap.create(); ticketsByPerson.put(jack, ctu); ticketsByPerson.put(jack, division); ticketsByPerson.get(jack); // asMap(), entries(), values()... Collections: Multimap<K, V> explain
  90. // Bi-directional map, keys and values are unique BiMap<K1, K2>

    // Two-tier map, or a map with two keys Table<R, C, V> Goodies! javadoc
  91. // Bi-directional map, keys and values are unique BiMap<K1, K2>

    // Two-tier map, or a map with two keys Table<R, C, V> // < JDK 7, no diamond support List<String> list = Lists.newArrayList(); // Sets, Maps... Goodies! javadoc
  92. // Bi-directional map, keys and values are unique BiMap<K1, K2>

    // Two-tier map, or a map with two keys Table<R, C, V> // < JDK 7, no diamond support List<String> list = Lists.newArrayList(); // Sets, Maps... // Ranges RangeSet<Integer> rangeSet = TreeRangeSet.create(); rangeSet.add(Range.closed(1, 10)); // {[1, 10]} Goodies! javadoc
  93. Freaking PHP: md5($string) public static String md5Java(String message) { String

    digest = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] hash = md.digest(message.getBytes("UTF-8")); String StringBuilder sb = new StringBuilder(2*hash.length); for(byte b : hash){ sb.append(String.format("%02x", b&0xff)); } digest = sb.toString(); } catch (UnsupportedEncodingException ex) { throw Throwables.propagate(ex); } catch (NoSuchAlgorithmException ex) { throw Throwables.propagate(ex); } return digest; } Hashing: JDK
  94. Freaking PHP: md5($string) public static String md5Java(String message) { String

    digest = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] hash = md.digest(message.getBytes("UTF-8")); String StringBuilder sb = new StringBuilder(2*hash.length); for(byte b : hash){ sb.append(String.format("%02x", b&0xff)); } digest = sb.toString(); } catch (UnsupportedEncodingException ex) { throw Throwables.propagate(ex); } catch (NoSuchAlgorithmException ex) { throw Throwables.propagate(ex); } return digest; } Hashing: JDK
  95. HashFunction hf = Hashing.md5(); HashCode hc = hf.newHasher() .putLong(id) .putString(name,

    Charsets.UTF_8) .putObject(person, personFunnel) .hash(); Hashing: Hasher
  96. HashFunction hf = Hashing.md5(); HashCode hc = hf.newHasher() .putLong(id) .putString(name,

    Charsets.UTF_8) .putObject(person, personFunnel) // Defines how to hash .hash(); Hashing: Hasher
  97. HashFunction hf = Hashing.md5(); HashCode hc = hf.newHasher() .putLong(id) .putString(name,

    Charsets.UTF_8) // HINT: remember this! .putObject(person, personFunnel) .hash(); Hashing: Hasher
  98. HashFunction hf = Hashing.md5(); HashCode hc = hf.newHasher() .putLong(id) .putString(name,

    Charsets.UTF_8) .putObject(person, personFunnel) .hash(); hc.asBytes(); // byte[] hc.asInt(); // value in little-endian order hc.toString(); // hexadecimal in lower case Hashing: Hasher
  99. // More hash functions! Hashing.md5(); Hashing.murmur3_32(); Hashing.murmur3_128(); Hashing.sha1(); Hashing.sha256(); Hashing.sha512();

    // Bloom Filter public boolean mightContain(T); if true, T is probably there if false, T for sure is not there Goodies! javadoc
  100. I/O

  101. Binary encoding scheme, RFC 4648 BaseEncoding .base32() .encode("foo".getBytes(Charsets.US_ASCII)); // returns

    MZXW6=== byte[] decoded = BaseEncoding .base32() .decode("MZXW6==="); I/O: BaseEncoding
  102. Binary encoding scheme, RFC 4648 BaseEncoding .base32() .encode("foo".getBytes(Charsets.US_ASCII)); // returns

    MZXW6=== byte[] decoded = BaseEncoding .base32() .decode("MZXW6==="); // returns the ASCII bytes of String “foo” I/O: BaseEncoding
  103. KIA