Guava Overview. Part 1 @ Bucharest JUG #1

1,790 views
1,670 views

Published on

The first part of a set of presentations about Google Guava at Bucharest JUG (Java User Group).

Published in: Technology, Education

Guava Overview. Part 1 @ Bucharest JUG #1

  1. 1. Guava Overview. Part 1 Andrei Savu / Bucharest JUG #1 asavu @ apache.org
  2. 2. About MeOwner / Engineer @ AxemblrApache Whirr PMC Memberjclouds committerWorked at Facebook & AdobeConnect with me on LinkedIn
  3. 3. @ AxemblrBuilding a tool and a platform for managingApache Hadoop clusters on cloud infrastructureThink Amazon EMR but for your cloud.Do you want to join? hello@axemblr.com
  4. 4. Plan● Introduction● Basic utilities● Collections● Strings● Primitives● Next & Questions
  5. 5. IntroductionOpen-source version of Googles core Javalibraries[...] carefully designed, tested, optimized andused in production at GoogleYou dont need to write them, test them, oroptimize them: you can just use them.
  6. 6. Introduction (cont)Battle-tested in production at GoogleStaggering numbers of unit tests. >110.000 asof January 2012 (generated)Lives near the bottom of the stack, right on topof the JDK itself
  7. 7. Plan● Introduction● Basic utilities 1.Using and avoiding null 2.Preconditions 3.Common object utilities 4.Ordering 5.
  8. 8. Using and avoiding null● careless use of null can cause bugs● most collections should not contain null values (95% @ Google)● null is ambiguous (e.g. Map.get)Avoid null by using:● "null object" pattern (e.g. empty collection)● null Map entries stored as a Set of null keys● Guava Optional<T>
  9. 9. Optional<T>As a replacement for null when used to indicatesome sort of absenceOptional<T> may either contain a non-nullreference to a T instance or nothing.Optional<Integer> possible = Optional.of(5);possible.isPresent(); // returns truepossible.get(); // returns 5
  10. 10. Making an OptionalOptional.of(T) - make optional of given non-nullvalue or fail fast on nullOptional.absent() - return an absent optional ofsome typeOptional.fromNullable(T) - turn value inOptional and treat null as absent
  11. 11. Query methodsboolean isPresent() - true if non-null instanceT get() - instance or IllegalStateExceptionT or(T) - present value or specified defaultT orNull() - inverse fromNullableSet<T> asSet() - set with single value or empty
  12. 12. Convenience methodsObjects.firstNonNull(T, T) orNullPointerException if both are nullStrings.emptyToNull(String)Strings.isNullOrEmpty(String)Strings.nullToEmpty(String)" these methods are primarily for interfacingwith unpleasant APIs that equate null stringsand empty strings "
  13. 13. Whats the point?" It forces you to actively think about the absentcase if you want your program to compile at all,since you have to actively unwrap the Optionaland address that case. "https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained
  14. 14. Plan● Introduction● Basic utilities 1.Using and avoiding null 2.Preconditions 3.Common object utilities 4.Ordering 5.
  15. 15. Preconditions● useful for validation● recommended to be used as static importsEach method has three variants: ● no extra arguments ● an extra object. Exception is obj.toString() ● an extra String & Objects. String.format like but only allows %s (GWT compat)
  16. 16. checkArgument(boolean)Throws IllegalArgumentException if false Used to validate method arguments
  17. 17. checkNotNull(T) Throws NullPointerException if nullReturns the value. Can be used inline.field = checkNotNull(input, "Message")
  18. 18. checkState(boolean)Throws IllegalStateException if false Used to check object state
  19. 19. checkElementIndex(index, size)Throws IndexOutOfBoundsException Interval [0, size) (exclusive)
  20. 20. checkPositionIndex(index, size)Throws IndexOutOfBoundsException Interval [0, size] (inclusive)
  21. 21. checkPositionIndexes(start, end, size) Throws IndexOutOfBoundsException [start, end) is valid sub-range of [0, size]
  22. 22. Plan● Introduction● Basic utilities 1.Using and avoiding null 2.Preconditions 3.Common object utilities 4.Ordering 5.
  23. 23. Objects.equal(X, Y) "a", "a" => true null, "a" => false "a", null => false null, null => true
  24. 24. Objects.hashCode(Object...)Easy to use, order-sensitive hash function
  25. 25. Objects.toStringHelper // Returns "ClassName{x=1}" Objects.toStringHelper(this) .add("X",1) .toString();
  26. 26. ComparisonChainHelper when implementing Comparator or theComparable interface.return ComparisonChain.start() .compare(this.aString, that.aString) .compare(this.anInt, that.anInt) .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast()) .result();Has a lazy behaviour.
  27. 27. Plan● Introduction● Basic utilities 1.Using and avoiding null 2.Preconditions 3.Common object utilities 4.Ordering 5.
  28. 28. Ordering OverviewGuavas "fluent" Comparator class.Quick example:
  29. 29. Ordering: CreationUsing static factory methods:● natural()● usingToString()● arbitrary() (constant for the life of the VM)● from(Comparator)
  30. 30. Ordering: Creation (cont)Or by extending the abstract class:
  31. 31. Ordering: Manipulation" A given Ordering can be modified to obtainmany other useful derived orderings "Common: reverse(), nullsFirst(), nullsLast(),lexicographical(), onResultOf(Function)
  32. 32. Ordering: Applicationor how to apply to values and collections.Common: greatestOf(it, k), leastOf(...),isOrdered(it), isStrictlyOrdered(it), sortedCopy(it), min(E... or iterable), max(E... or iterable)
  33. 33. Plan● Introduction● Basic utilities● Collections Immutable Collections New types Collection Utilities Extension Utilities
  34. 34. Example
  35. 35. Why immutable?● safe for use by untrusted libraries● thread-safe● more efficient, time & space (analysis)● can be used as a constant
  36. 36. How?Immutable** can be created in several ways:● copyOf(T) e.g. ImmutableSet.copyOf(set)● of(elements) e.g. ImmutableMap.of("a", "b")● using a BuilderAll collections support asList (const. time view)
  37. 37. Plan● Introduction● Basic utilities● Collections Immutable Collections New types Collection Utilities Extension Utilities
  38. 38. Multiset
  39. 39. Multiset Operationscount(E), add(E, int), remove(E, int), setCount(E, int), size()elementSet() - distinct elements as setentrySet() - similar to Map.entrySet() returnsSet<Multiset.Entry<E>>, supports getElement()and getCount()
  40. 40. Multiset ImplementationsHashMultisetTreeMultisetLinkedHashMultisetConcurrentHashMultisetImmutableMultiset
  41. 41. SortedMultisetVariation of Multiset that supports efficientlytaking sub-multisets on specified ranges.latencies.subMultiset(0, BoundType.CLOSED,100, BoundType.OPEN).size()
  42. 42. MultimapListMultimap & SetMultimapMap<String, List<T>> & Map<String, Set<T>>Operations: put(K, V), putAll(K, Iterable<V>),remove(K, V), removeAll(K, Iterable<V>),replaceValues(K, Iterable<V>)
  43. 43. Multimap Implementations
  44. 44. BiMapBiMap<K, V> is Map<K,V> with unique valuesOperations: all Map, inverse(), values() as SetThrows an IllegalArgumentException if youattempt to map a key to an already-presentvalue
  45. 45. BiMap Implementations
  46. 46. Table
  47. 47. Plan● Introduction● Basic utilities● Collections Immutable Collections New types Collection Utilities Extension Utilities
  48. 48. Iterables & FluentIterable (Guava 12)http://docs.guava-libraries.googlecode.com/git-history/release12/javadoc/com/google/common/collect/FluentIterable.htmlhttp://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Iterables.html
  49. 49. Plan● Introduction● Basic utilities● Collections Immutable Collections New types Collection Utilities Extension Utilities as ways of extending the collections framework
  50. 50. Forwarding Decorators
  51. 51. Peeking Iteratoras an iterator that supports peek()Remove consecutive duplicates:
  52. 52. Abstract Iterator
  53. 53. Plan● Introduction● Basic utilities● Collections● Strings
  54. 54. Joiner thread-safe & immutable
  55. 55. Splitter
  56. 56. CharMatcher
  57. 57. Types of CharMatchers
  58. 58. Charsets"Charsets provides constant references to thesix standard Charset implementationsguaranteed to be supported by all Javaplatform implementations."bytes = string.getBytes(Charsets.UTF_8);
  59. 59. CaseFormat
  60. 60. Plan● Introduction● Basic utilities● Collections● Strings● Primitives
  61. 61. Array UtilitiesList<Wrapper> asList(prim... backingArray)prim[] toArray(Collection<Wrapper> collection)prim[] concat(prim[]... arrays)boolean contains(prim[] array, prim target)int indexOf(prim[] array, prim target)int lastIndexOf(prim[] array, prim target)prim min(prim... array)prim max(prim... array)String join(String separator, prim... array)
  62. 62. Next edition?CachesFunctional IdiomsConcurrencyRangesI/OHashingEventBusMathReflection
  63. 63. Thanks! Questions?Andrei Savu / asavu @ apache.org

×