Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Google Guava

4,098 views

Published on

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

Published in: Technology, News & Politics
  • Be the first to comment

Google Guava

  1. 1. GoogleGuavaScottLeberknight
  2. 2. "Guava is the open-sourced version ofGoogles core Java libraries: the core utilitiesthat Googlers use every day in their code."
  3. 3. "Guava has been battle-tested inproduction at Google"
  4. 4. "Guava has staggering numbers of unittests: as of July 2012, the guava-testspackage includes over 286,000individual test cases."WAT???
  5. 5. "Guava is under active development andhas a strong, vocal, and involved user base."
  6. 6. collectionsconcurrencyprimitivesreflectioncomparisonI/omathstringshashingcachingin-memory pub/subnet/http
  7. 7. Examples...
  8. 8. preconditionscheckArgument(age >= drinkingAge,"age must be greater than %s", drinkingAge);checkNotNull(input, "input cannot be null");
  9. 9. "Null sucks" - Doug Lea
  10. 10. avoiding nullsOptional<String> value = Optional.fromNullable(str);if (value.isPresent()) {// ...}
  11. 11. joining stringsList<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"
  12. 12. splitting stringsString input = ",, ,apple, orange ,,, banana,, ,guava, ,,";Iterable<String> split =Splitter.on(,).omitEmptyStrings().trimResults().split(input);// [ "apple", "orange", "banana", "guava" ]
  13. 13. CharMatcherCharMatcher 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);
  14. 14. ObjectsObjects.equalObjects.toStringHelpercompareTo() via ComparisonChainOrdering
  15. 15. MultisetTrack frequencies ofelements, 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 timesn", word, count);}
  16. 16. Map<String, List<String>>Tired of this?
  17. 17. MultimapMultimap<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" ]
  18. 18. SetsSet<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"
  19. 19. TableTable<R, C, V>
  20. 20. Ranges &DomainsRange<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 ]
  21. 21. FP in GuavaFluentIterable<Integer> squaresOfEvens = FluentIterable.from(numbers).filter(new Predicate<Integer>() {@Overridepublic boolean apply(@Nullable Integer input) {checkNotNull(input, "nulls are not allowed here!");return input % 2 == 0;}}).transform(new Function<Integer, Integer>() {@Nullable@Overridepublic Integer apply(@Nullable Integer input) {checkNotNull(input, "nulls are not allowed here!");return input * input;}});// [ 4, 16, 36, 64, 100 ]WAT?
  22. 22. 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 ]
  23. 23. "Excessive use of Guavas functional programming idiomscan lead to verbose, confusing, unreadable, and inefficientcode.These are by far the most easily (and mostcommonly) abused parts of Guava, and when you go topreposterous lengths to make your code "a one-liner," theGuava team weeps."
  24. 24. 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>() {@Overridepublic void onSuccess(WorkResult result) {// do something after success...}@Overridepublic void onFailure(Throwable t) {// handle error...}}, executorService););
  25. 25. @Beta"...subject to change..."
  26. 26. "Guava deprecates, and yes, deletesunwanted features over time. It isimportant to us that when you see afeature in the Javadocs, it representsthe Guava teams best work, and nota feature that in retrospect was a badidea."
  27. 27. Get someGuava!
  28. 28. Referenceshttps://code.google.com/p/guava-libraries/https://code.google.com/p/guava-libraries/wiki/GuavaExplainedhttps://code.google.com/p/guava-libraries/downloads/listhttp://docs.guava-libraries.googlecode.com/git-history/release/javadoc/index.htmlhttp://www.tfnico.com/presentations/google-guavahttp://codingjunkie.net/tag/guava/
  29. 29. Photo Attributions* this one is iStockPhoto (paid) -->http://www.morguefile.com/archive/display/138854http://www.flickr.com/photos/hermansaksono/4297175782/http://commons.wikimedia.org/wiki/File:Guava_ID.jpghttp://www.flickr.com/photos/88845568@N00/2076930689/http://www.flickr.com/photos/mohannad_khatib/6352720649/
  30. 30. https://github.com/sleberknight/google-guava-samplesSample codeavailable at:
  31. 31. My Infoscott dot leberknight at nearinfinity dot comtwitter.com/sleberknight www.sleberknight.com/blogwww.nearinfinity.com/blogs/scott_leberknight/all/scott dot leberknight at gmail dot com

×