32
Google Guava Scott Leberknight

Google Guava

Embed Size (px)

DESCRIPTION

Slides for presentation on Google Guava I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference. The associated sample code is on GitHub at https://github.com/sleberknight/google-guava-samples

Citation preview

Page 1: Google Guava

Google Guava

Scott Leberknight

Page 2: Google Guava

"Guava is the open-sourced version of Google's core Java libraries: the core utilities that Googlers use every day in their code."

Page 3: Google Guava

"Guava has been battle-tested in production at Google"

Page 4: Google Guava

"Guava has staggering numbers of unit tests: as of July 2012, the guava-tests package includes over 286,000 individual test cases."

WAT???

Page 5: Google Guava

"Guava is under active development and has a strong, vocal, and involved user base."

Page 6: Google Guava

collections

concurrency

primitives

reflection

comparison

I/o

math

strings

hashing

caching

in-memory pub/sub

net/http

Page 7: Google Guava

Examples...

Page 8: Google Guava

preconditions

checkArgument(age >= drinkingAge, "age must be greater than %s", drinkingAge);

checkNotNull(input, "input cannot be null");

Page 9: Google Guava

"Null sucks" - Doug Lea

Page 10: Google Guava

avoiding nulls

Optional<String> value = Optional.fromNullable(str);if (value.isPresent()) { // ...}

Page 11: Google Guava

joining strings

List<String> fruits = Arrays.asList("apple", null, "orange", null, null, "guava");String joined = Joiner.on(", ").skipNulls().join(fruits);// "apple, orange, guava"

List<String> fruits = Arrays.asList("apple", null, "orange", null, null, "guava");String joined = Joiner.on(", ).useForNull("banana").join(fruits);// "apple, banana, orange, banana, banana, guava"

Page 12: Google Guava

splitting strings

String input = ",, ,apple, orange ,,, banana,, ,guava, ,,";Iterable<String> split = Splitter.on(',').omitEmptyStrings().trimResults().split(input);// [ "apple", "orange", "banana", "guava" ]

Page 13: Google Guava

CharMatcher

CharMatcher matcher = CharMatcher.DIGIT.or(inRange('a', 'z').or(inRange('A', 'Z')));if (matcher.matchesAllOf("this1will2match3")) { // ...}

String input = " secret passcode ";String result = CharMatcher.WHITESPACE.trimFrom(input);

Page 14: Google Guava

Objects

Objects.equal

Objects.toStringHelper

compareTo() via ComparisonChain

Ordering

Page 15: Google Guava

Multiset

Track frequencies of elements, e.g. "word counting"

Iterable<String> words = Splitter.on(' ').split(document);Multiset<String> wordCounts = HashMultiset.create(words);for (Multiset.Entry<String> entry : wordCounts.entrySet()) { String word = entry.getElement(); int count = counts.count(element); System.out.printf("%s appears %d times\n", word, count);}

Page 16: Google Guava

Map<String, List<String>>

Tired of this?

Page 17: Google Guava
Page 18: Google Guava

Multimap

Multimap<String, String> mm = ArrayListMultimap.create();

Collection<String> smiths = mm.get("Smith");// empty collection (never null)

mm.put("Smith", "John");mm.put("Smith", "Alice");mm.put("Smith", "Diane");

smiths = mm.get("Smith");// [ "John", "Alice", "Diane" ]

Page 19: Google Guava

Sets

Set<String> set1 = Sets.newHashSet("apple", "orange", "guava");Set<String> set2 = Sets.newHashSet("guava", "clementine");

Sets.SetView<String> diff1to2 = Sets.difference(set1, set2);// "apple", "orange"

Sets.SetView<String> diff2to1 = Sets.difference(set2, set1);// "clementine"

Page 20: Google Guava

Table

Table<R, C, V>

Page 21: Google Guava

Ranges & Domains

Range<Integer> range = Range.openClosed(0, 10);ContiguousSet<Integer> contiguousSet = ContiguousSet.create(range, DiscreteDomain.integers());ImmutableList<Integer> numbers = contiguousSet.asList();// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Page 22: Google Guava

FP in Guava

FluentIterable<Integer> squaresOfEvens = FluentIterable.from(numbers) .filter(new Predicate<Integer>() { @Override public boolean apply(@Nullable Integer input) { checkNotNull(input, "nulls are not allowed here!"); return input % 2 == 0; } }) .transform(new Function<Integer, Integer>() { @Nullable @Override public Integer apply(@Nullable Integer input) { checkNotNull(input, "nulls are not allowed here!"); return input * input; } });// [ 4, 16, 36, 64, 100 ]

WAT?

Page 23: Google Guava

Until Java 8...

List<Integer> squaresOfEvens = Lists.newArrayList();for (Integer number : numbers) { if (number % 2 == 0) { squaresOfEvens.add(number * number); }}// [ 4, 16, 36, 64, 100 ]

Page 24: Google Guava

"Excessive use of Guava's functional programming idioms can lead to verbose, confusing, unreadable, and inefficient code. These are by far the most easily (and most commonly) abused parts of Guava, and when you go to preposterous lengths to make your code "a one-liner," the Guava team weeps."

Page 25: Google Guava

ListenableFuture// setup...ExecutorService delegate = Executors.newFixedThreadPool(MAX_THREADS);ListeningExecutorService executorService = MoreExecutors.listeningDecorator(delegate);

// submit tasks...ListenableFuture<WorkResult> future = executorService.submit(worker);Futures.addCallback(future, new FutureCallback<WorkResult>() { @Override public void onSuccess(WorkResult result) { // do something after success... }

@Override public void onFailure(Throwable t) { // handle error... }}, executorService););

Page 26: Google Guava

@Beta"...subject to change..."

Page 27: Google Guava

"Guava deprecates, and yes, deletes unwanted features over time. It is important to us that when you see a feature in the Javadocs, it represents the Guava team's best work, and not a feature that in retrospect was a bad idea."

Page 28: Google Guava

Get some

Guava!

Page 29: Google Guava

References

https://code.google.com/p/guava-libraries/

https://code.google.com/p/guava-libraries/wiki/GuavaExplained

https://code.google.com/p/guava-libraries/downloads/list

http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/index.html

http://www.tfnico.com/presentations/google-guava

http://codingjunkie.net/tag/guava/

Page 30: Google Guava

Photo Attributions

* this one is iStockPhoto (paid) -->

http://www.morguefile.com/archive/display/138854

http://www.flickr.com/photos/hermansaksono/4297175782/

http://commons.wikimedia.org/wiki/File:Guava_ID.jpg

http://www.flickr.com/photos/88845568@N00/2076930689/

http://www.flickr.com/photos/mohannad_khatib/6352720649/

Page 31: Google Guava

https://github.com/sleberknight/google-guava-samples

Sample code available at:

Page 32: Google Guava

My Infoscott dot leberknight at nearinfinity dot com

twitter.com/sleberknight www.sleberknight.com/blog

www.nearinfinity.com/blogs/scott_leberknight/all/

scott dot leberknight at gmail dot com