Guava Overview. Part 1 @ Bucharest JUG #1
-
Upload
andrei-savu -
Category
Technology
-
view
1.449 -
download
0
description
Transcript of Guava Overview. Part 1 @ Bucharest JUG #1
Guava Overview. Part 1Andrei Savu / Bucharest JUG #1
asavu @ apache.org
Owner / Engineer @ Axemblr Apache Whirr PMC Memberjclouds committer Worked at Facebook & AdobeConnect with me on LinkedIn
About Me
@ Axemblr
Building a tool and a platform for managing Apache Hadoop clusters on cloud infrastructure Think Amazon EMR but for your cloud. Do you want to join? [email protected]
Plan
● Introduction● Basic utilities● Collections● Strings● Primitives● Next & Questions
Introduction
Open-source version of Google's core Java libraries [...] carefully designed, tested, optimized and used in production at Google You don't need to write them, test them, or optimize them: you can just use them.
Introduction (cont)
Battle-tested in production at Google Staggering numbers of unit tests. >110.000 as of January 2012 (generated) Lives near the bottom of the stack, right on top of the JDK itself
Plan
● Introduction● Basic utilities
1. Using and avoiding null2. Preconditions3. Common object utilities4. Ordering5.
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>
Optional<T>
As a replacement for null when used to indicate some sort of absence Optional<T> may either contain a non-null reference to a T instance or nothing. Optional<Integer> possible = Optional.of(5);possible.isPresent(); // returns truepossible.get(); // returns 5
Making an Optional
Optional.of(T) - make optional of given non-null value or fail fast on null Optional.absent() - return an absent optional of some type Optional.fromNullable(T) - turn value in Optional and treat null as absent
Query methods
boolean isPresent() - true if non-null instance T get() - instance or IllegalStateException T or(T) - present value or specified default T orNull() - inverse fromNullable Set<T> asSet() - set with single value or empty
Convenience methods
Objects.firstNonNull(T, T) or NullPointerException if both are null Strings.emptyToNull(String)Strings.isNullOrEmpty(String)Strings.nullToEmpty(String) " these methods are primarily for interfacing with unpleasant APIs that equate null strings and empty strings "
What's the point?
" It forces you to actively think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional and address that case. " https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained
Plan
● Introduction● Basic utilities
1. Using and avoiding null2. Preconditions3. Common object utilities4. Ordering5.
Preconditions
● useful for validation● recommended to be used as static imports Each 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)
checkArgument(boolean)Throws IllegalArgumentException if false
Used to validate method arguments
Throws NullPointerException if nullReturns the value. Can be used inline.
field = checkNotNull(input, "Message")
checkNotNull(T)
Throws IllegalStateException if falseUsed to check object state
checkState(boolean)
Throws IndexOutOfBoundsExceptionInterval [0, size) (exclusive)
checkElementIndex(index, size)
Throws IndexOutOfBoundsExceptionInterval [0, size] (inclusive)
checkPositionIndex(index, size)
Throws IndexOutOfBoundsException[start, end) is valid sub-range of [0, size]
checkPositionIndexes(start, end, size)
Plan
● Introduction● Basic utilities
1. Using and avoiding null2. Preconditions3. Common object utilities4. Ordering5.
Objects.equal(X, Y)"a", "a" => true
null, "a" => false"a", null => falsenull, null => true
Easy to use, order-sensitive hash function
Objects.hashCode(Object...)
// Returns "ClassName{x=1}"Objects.toStringHelper(this)
.add("X",1).toString();
Objects.toStringHelper
Helper when implementing Comparator or the Comparable 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.
ComparisonChain
Plan
● Introduction● Basic utilities
1. Using and avoiding null2. Preconditions3. Common object utilities4. Ordering5.
Ordering Overview
Guava's "fluent" Comparator class. Quick example:
Ordering: Creation
Using static factory methods:● natural() ● usingToString()● arbitrary() (constant for the life of the VM)● from(Comparator)
Ordering: Creation (cont)
Or by extending the abstract class:
Ordering: Manipulation
" A given Ordering can be modified to obtain many other useful derived orderings " Common: reverse(), nullsFirst(), nullsLast(), lexicographical(), onResultOf(Function)
Ordering: Application
or 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)
Plan
● Introduction● Basic utilities● Collections
Immutable CollectionsNew typesCollection UtilitiesExtension Utilities
Example
Why immutable?
● safe for use by untrusted libraries● thread-safe● more efficient, time & space (analysis)● can be used as a constant
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 Builder All collections support asList (const. time view)
Plan
● Introduction● Basic utilities● Collections
Immutable CollectionsNew typesCollection UtilitiesExtension Utilities
Multiset
Multiset Operations
count(E), add(E, int), remove(E, int), setCount(E, int), size() elementSet() - distinct elements as setentrySet() - similar to Map.entrySet() returns Set<Multiset.Entry<E>>, supports getElement() and getCount()
Multiset Implementations
HashMultisetTreeMultisetLinkedHashMultisetConcurrentHashMultisetImmutableMultiset
SortedMultiset
Variation of Multiset that supports efficiently taking sub-multisets on specified ranges. latencies.subMultiset(0, BoundType.CLOSED, 100, BoundType.OPEN).size()
Multimap
ListMultimap & SetMultimap Map<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>)
Multimap Implementations
BiMap
BiMap<K, V> is Map<K,V> with unique values Operations: all Map, inverse(), values() as Set Throws an IllegalArgumentException if you attempt to map a key to an already-present value
BiMap Implementations
Table
Plan
● Introduction● Basic utilities● Collections
Immutable CollectionsNew typesCollection UtilitiesExtension Utilities
Iterables & FluentIterable (Guava 12)
http://docs.guava-libraries.googlecode.com/git-history/release12/javadoc/com/google/common/collect/FluentIterable.html http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Iterables.html
Plan
● Introduction● Basic utilities● Collections
Immutable CollectionsNew typesCollection UtilitiesExtension Utilities
as ways of extending the collections framework
Forwarding Decorators
Peeking Iterator
as an iterator that supports peek() Remove consecutive duplicates:
Abstract Iterator
Plan
● Introduction● Basic utilities● Collections● Strings
thread-safe & immutable
Joiner
Splitter
CharMatcher
Types of CharMatchers
Charsets
"Charsets provides constant references to the six standard Charset implementations guaranteed to be supported by all Java platform implementations." bytes = string.getBytes(Charsets.UTF_8);
CaseFormat
Plan
● Introduction● Basic utilities● Collections● Strings● Primitives
Array Utilities
List<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)
Next edition?
CachesFunctional IdiomsConcurrencyRangesI/OHashingEventBusMathReflection
Thanks! Questions?Andrei Savu / asavu @ apache.org