guava overview. part 1 @ bucharest jug #1

67
Guava Overview. Part 1 Andrei Savu / Bucharest JUG #1 asavu @ apache.org

Upload: andrei-savu

Post on 06-May-2015

1.451 views

Category:

Technology


0 download

DESCRIPTION

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

TRANSCRIPT

Page 1: Guava Overview. Part 1 @ Bucharest JUG #1

Guava Overview. Part 1Andrei Savu / Bucharest JUG #1

asavu @ apache.org

Page 2: Guava Overview. Part 1 @ Bucharest JUG #1

Owner / Engineer @ Axemblr Apache Whirr PMC Memberjclouds committer Worked at Facebook & AdobeConnect with me on LinkedIn

About Me

Page 3: Guava Overview. Part 1 @ Bucharest JUG #1

@ 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]

Page 4: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities● Collections● Strings● Primitives● Next & Questions

Page 5: Guava Overview. Part 1 @ Bucharest JUG #1

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.

Page 6: Guava Overview. Part 1 @ Bucharest JUG #1

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

Page 7: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities

1. Using and avoiding null2. Preconditions3. Common object utilities4. Ordering5.

Page 8: Guava Overview. Part 1 @ Bucharest JUG #1

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>

Page 9: Guava Overview. Part 1 @ Bucharest JUG #1

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

Page 10: Guava Overview. Part 1 @ Bucharest JUG #1

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

Page 11: Guava Overview. Part 1 @ Bucharest JUG #1

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

Page 12: Guava Overview. Part 1 @ Bucharest JUG #1

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 "

Page 13: Guava Overview. Part 1 @ Bucharest JUG #1

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

Page 14: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities

1. Using and avoiding null2. Preconditions3. Common object utilities4. Ordering5.

Page 15: Guava Overview. Part 1 @ Bucharest JUG #1

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)

Page 16: Guava Overview. Part 1 @ Bucharest JUG #1

checkArgument(boolean)Throws IllegalArgumentException if false

Used to validate method arguments

Page 17: Guava Overview. Part 1 @ Bucharest JUG #1

Throws NullPointerException if nullReturns the value. Can be used inline.

field = checkNotNull(input, "Message")

checkNotNull(T)

Page 18: Guava Overview. Part 1 @ Bucharest JUG #1

Throws IllegalStateException if falseUsed to check object state

checkState(boolean)

Page 19: Guava Overview. Part 1 @ Bucharest JUG #1

Throws IndexOutOfBoundsExceptionInterval [0, size) (exclusive)

checkElementIndex(index, size)

Page 20: Guava Overview. Part 1 @ Bucharest JUG #1

Throws IndexOutOfBoundsExceptionInterval [0, size] (inclusive)

checkPositionIndex(index, size)

Page 21: Guava Overview. Part 1 @ Bucharest JUG #1

Throws IndexOutOfBoundsException[start, end) is valid sub-range of [0, size]

checkPositionIndexes(start, end, size)

Page 22: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities

1. Using and avoiding null2. Preconditions3. Common object utilities4. Ordering5.

Page 23: Guava Overview. Part 1 @ Bucharest JUG #1

Objects.equal(X, Y)"a", "a" => true

null, "a" => false"a", null => falsenull, null => true

Page 24: Guava Overview. Part 1 @ Bucharest JUG #1

Easy to use, order-sensitive hash function

Objects.hashCode(Object...)

Page 25: Guava Overview. Part 1 @ Bucharest JUG #1

// Returns "ClassName{x=1}"Objects.toStringHelper(this)

.add("X",1).toString();

Objects.toStringHelper

Page 26: Guava Overview. Part 1 @ Bucharest JUG #1

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

Page 27: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities

1. Using and avoiding null2. Preconditions3. Common object utilities4. Ordering5.

Page 28: Guava Overview. Part 1 @ Bucharest JUG #1

Ordering Overview

Guava's "fluent" Comparator class. Quick example:

Page 29: Guava Overview. Part 1 @ Bucharest JUG #1

Ordering: Creation

Using static factory methods:● natural() ● usingToString()● arbitrary() (constant for the life of the VM)● from(Comparator)

Page 30: Guava Overview. Part 1 @ Bucharest JUG #1

Ordering: Creation (cont)

Or by extending the abstract class:

Page 31: Guava Overview. Part 1 @ Bucharest JUG #1

Ordering: Manipulation

" A given Ordering can be modified to obtain many other useful derived orderings " Common: reverse(), nullsFirst(), nullsLast(), lexicographical(), onResultOf(Function)

Page 32: Guava Overview. Part 1 @ Bucharest JUG #1

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)

Page 33: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities● Collections

Immutable CollectionsNew typesCollection UtilitiesExtension Utilities

Page 34: Guava Overview. Part 1 @ Bucharest JUG #1

Example

Page 35: Guava Overview. Part 1 @ Bucharest JUG #1

Why immutable?

● safe for use by untrusted libraries● thread-safe● more efficient, time & space (analysis)● can be used as a constant

Page 36: Guava Overview. Part 1 @ Bucharest JUG #1

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)

Page 37: Guava Overview. Part 1 @ Bucharest JUG #1
Page 38: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities● Collections

Immutable CollectionsNew typesCollection UtilitiesExtension Utilities

Page 39: Guava Overview. Part 1 @ Bucharest JUG #1

Multiset

Page 40: Guava Overview. Part 1 @ Bucharest JUG #1

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()

Page 41: Guava Overview. Part 1 @ Bucharest JUG #1

Multiset Implementations

HashMultisetTreeMultisetLinkedHashMultisetConcurrentHashMultisetImmutableMultiset

Page 42: Guava Overview. Part 1 @ Bucharest JUG #1

SortedMultiset

Variation of Multiset that supports efficiently taking sub-multisets on specified ranges. latencies.subMultiset(0, BoundType.CLOSED, 100, BoundType.OPEN).size()

Page 43: Guava Overview. Part 1 @ Bucharest JUG #1

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>)

Page 44: Guava Overview. Part 1 @ Bucharest JUG #1

Multimap Implementations

Page 45: Guava Overview. Part 1 @ Bucharest JUG #1

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

Page 46: Guava Overview. Part 1 @ Bucharest JUG #1

BiMap Implementations

Page 47: Guava Overview. Part 1 @ Bucharest JUG #1

Table

Page 48: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities● Collections

Immutable CollectionsNew typesCollection UtilitiesExtension Utilities

Page 49: Guava Overview. Part 1 @ Bucharest JUG #1
Page 51: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities● Collections

Immutable CollectionsNew typesCollection UtilitiesExtension Utilities

as ways of extending the collections framework

Page 52: Guava Overview. Part 1 @ Bucharest JUG #1

Forwarding Decorators

Page 53: Guava Overview. Part 1 @ Bucharest JUG #1
Page 54: Guava Overview. Part 1 @ Bucharest JUG #1

Peeking Iterator

as an iterator that supports peek() Remove consecutive duplicates:

Page 55: Guava Overview. Part 1 @ Bucharest JUG #1

Abstract Iterator

Page 56: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities● Collections● Strings

Page 57: Guava Overview. Part 1 @ Bucharest JUG #1

thread-safe & immutable

Joiner

Page 58: Guava Overview. Part 1 @ Bucharest JUG #1

Splitter

Page 59: Guava Overview. Part 1 @ Bucharest JUG #1

CharMatcher

Page 60: Guava Overview. Part 1 @ Bucharest JUG #1

Types of CharMatchers

Page 61: Guava Overview. Part 1 @ Bucharest JUG #1

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);

Page 62: Guava Overview. Part 1 @ Bucharest JUG #1

CaseFormat

Page 63: Guava Overview. Part 1 @ Bucharest JUG #1

Plan

● Introduction● Basic utilities● Collections● Strings● Primitives

Page 64: Guava Overview. Part 1 @ Bucharest JUG #1
Page 65: Guava Overview. Part 1 @ Bucharest JUG #1

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)

Page 66: Guava Overview. Part 1 @ Bucharest JUG #1

Next edition?

CachesFunctional IdiomsConcurrencyRangesI/OHashingEventBusMathReflection

Page 67: Guava Overview. Part 1 @ Bucharest JUG #1

Thanks! Questions?Andrei Savu / asavu @ apache.org