Google Guava

Post on 15-Jan-2015

1,612 views 8 download

Tags:

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

transcript

Google Guava

Scott Leberknight

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

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

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

WAT???

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

collections

concurrency

primitives

reflection

comparison

I/o

math

strings

hashing

caching

in-memory pub/sub

net/http

Examples...

preconditions

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

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

"Null sucks" - Doug Lea

avoiding nulls

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

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"

splitting strings

String input = ",, ,apple, orange ,,, banana,, ,guava, ,,";Iterable<String> split = Splitter.on(',').omitEmptyStrings().trimResults().split(input);// [ "apple", "orange", "banana", "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);

Objects

Objects.equal

Objects.toStringHelper

compareTo() via ComparisonChain

Ordering

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

Map<String, List<String>>

Tired of this?

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

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"

Table

Table<R, C, V>

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 ]

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?

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 ]

"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."

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

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

"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."

Get some

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/

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/

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

Sample code available at:

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