SlideShare a Scribd company logo
1 of 113
Download to read offline


Guava is…
Guava is…
a fruit
https://en.wikipedia.org/wiki/Guava
What is Google Guava?
annotations
basic utilities
collections
concurrency
comparison
strings
primitives
ranges
functional idioms
I/o
caching
hashing
event bus
math
reflection
net/http
What in this presentation?
annotations
basic utilities
collections
concurrency
comparison
strings
primitives
ranges
functional idioms
I/O
caching
hashing
event bus
math
reflection
net/http
Why Guava?
 The goal is for you to write less code ...
 Make code more readable, cleaner and simpler
 Helps developers to focus on business logic rather
than writing java utilities
 Saves time, resources and improve productivity
 Popular API and active development
 Mainstream
 Basically... a painkiller and natural extension for Java
I Could've Invented That
ref. Effective Java
Item 47, "Know and use the libraries“
Guava Releases
 About every 3 months, with significant new
functionality and fixes
 Release 14.0.1 was released on March 15, 2013
 All releases are either major or patch releases
 Never minor
Let’s get some Guava!
@annotations
Guava Basic Utilities
 String Utilities
 Preconditions
 Objects Helper
 Avoiding Nulls
 StopWatch
String Utilities
 Joiner
 Splitter
 CharMatcher
Joining Strings
 Who here has ever written this utility?
public class StringUtil {
public static String join(
String separator, Iterable<String> pieces) {
// any of ~5 common implementations goes here
}
}
Joining Strings
 Converts collections into single String object
 Joining an Iterable, Iterator, varargs/array
 Return a String, or append to an Appendable
 Throws a NPE on null objects, unless:
 .skipNulls()
 .useForNull(String)
 It also works with Maps
 We could be looking at 18 to 48 different methods
Joining Strings (cont.)
List<String> fruits = Arrays.asList(
"apple", null, "orange", null, null, "guava");
String joined = Joiner.on(", ").skipNulls().join(fruits);
>> "apple, orange, guava"
Joining Strings (cont.)
List<String> fruits = Arrays.asList(
"apple", null, "orange", null, null, "guava");
String joined = Joiner.on(", ").skipNulls().join(fruits);
>> "apple, orange, guava"
String joined = Joiner.on(",").useForNull("banana").join(fruits);
>> "apple, banana, orange, banana, banana, guava"
Splitting Strings
 Working in the opposite direction than Joiner
 Allows to split String into collection of elements
 String.split() on steroids 
 A better, more intuitive String.split()
 Doesn't silently discard trailing separators
 Handles empty pieces predictably
Splitter
String input = ",, ,apple, orange ,,, banana,, ,guava, ,,";
Iterable<String> split = Splitter.on(',')
.omitEmptyStrings()
.trimResults()
.split(input);
>> [ "apple", "orange", "banana", "guava" ]
 The default behavior is simplistic
 If you want extra features, ask for them!
Splitter
String input = ",, ,apple, orange ,,, banana,, ,guava, ,,";
Iterable<String> split = Splitter.on(',')
.omitEmptyStrings()
.trimResults()
.split(input);
>> [ "apple", "orange", "banana", "guava" ]
 The default behavior is simplistic
 If you want extra features, ask for them!
 By default, assumes nothing about whitespace
 These classes use what Googlers (tentatively) call the "Utility Object pattern."
Splitter more…
Splitter.onPattern("d+").split("Java3Scala4Haskell0Brainfuck5Kotlin");
>> [ "Java ", "Scala", "Haskell", "Brainfuck", "Kotlin" ]
Splitter.on(CharMatcher.inRange('3','5'))
.split("Java3Scala4Haskell0Brainfuck5Kotlin");
>> [ "Java", "Scala", "Haskell0Brainfuck", "Kotlin" ]
 Split using regular expression
 Split using CharMatcher
CharMatcher
 CharMatcher provides many text processing
methods based on “matching character” notation
 Separates "configuration" from "processing"
 CharMatcher represents two notions:
 What constitutes a matching character?
 What to do with those matching characters?
 Can also be used to "filter" chars
CharMatcher (cont.)
 Allows to check if a sequence of characters satisfies
given condition:
WHITESPACE, ASCII, ANY, DIGIT (many pre-defined sets)
is('x')
isNot('_')
oneOf("aeiou")
inRange('a', 'z') .or (inRange('A', 'Z')).negate()
All that you can do... CharMatcher
 Provides methods to modify char sequences:
boolean matchesAllOf(CharSequence)
boolean matchesAnyOf(CharSequence)
boolean matchesNoneOf(CharSequence)
int indexIn(CharSequence, int)
int lastIndexIn(CharSequence, int)
int countIn(CharSequence)
String removeFrom(CharSequence)
String retainFrom(CharSequence)
String trimFrom(CharSequence)
String trimLeadingFrom(CharSequence)
String trimTrailingFrom(CharSequence)
String collapseFrom(CharSequence, char)
String trimAndCollapseFrom(CharSequence, char)
String replaceFrom(CharSequence, char)
CharMatcher (example)
CharMatcher matcher = CharMatcher.DIGIT
.or(CharMatcher.inRange('a', 'z')
.or(CharMatcher.inRange('A', 'Z')));
if (matcher.matchesAllOf("this1will2match3")) {
// ...
}
CharMatcher (example)
// eliminate all characters that aren't digits or lowercase
String lowerAndDigit = CharMatcher.DIGIT
.or(CharMatcher.JAVA_LOWER_CASE)
.retainFrom(input);
CharMatcher matcher = CharMatcher.DIGIT
.or(CharMatcher.inRange('a', 'z')
.or(CharMatcher.inRange('A', 'Z')));
if (matcher.matchesAllOf("this1will2match3")) {
// ...
}
CharMatcher (example)
String pass = “$$$ secret passcode $$$";
String result = CharMatcher.is(“$”).trimFrom(pass);
>> “ secret password "
trimLeadingFrom(), trimTrailingFrom() or trimAndCollapseFrom()
Guava Basic Utilities
 String Utilities
 Preconditions
 Objects Helper
 Avoiding Nulls
 StopWatch
checkState(boolean)
 Throws IllegalStateException if false
 Used to check object state
if (state != State.PLAYABLE) {
throw new IllegalStateException(
"Can't play movie; state is " + state);
}
checkState(boolean)
 Throws IllegalStateException if false
 Used to check object state
… or…
if (state != State.PLAYABLE) {
throw new IllegalStateException(
"Can't play movie; state is " + state);
}
Preconditions.checkState(state == State.PLAYABLE,
"Can't play movie; state is %s", state);
(what's the difference? none!)
checkNotNull(T)
 Throws NullPointerException if null
 Returns the value. Can be used inline.
public Car(Engine engine) {
this.engine = Preconditions.checkNotNull(engine);
}
checkNotNull(T)
 Throws NullPointerException if null
 Returns the value. Can be used inline.
. . . with using static import . . .
public Car(Engine engine) {
this.engine = Preconditions.checkNotNull(engine);
}
public Car(Engine engine) {
this.engine = checkNotNull(engine,
“engine cannot be null”);
}
checkArgument(boolean)
 Throws IllegalArgumentException if false
 Used to validate method arguments
public void drive(double speed) {
Preconditions.checkArgument(speed > 0.0,
"Speed (%s) must be positive", speed);
}
Why Preconditions?
 Defensive coding 
 Useful for validation
 Each method has three variants:
 No extra arguments
 An extra object for error message
 An extra String & Objects. String.format like
but only allows %s
 Recommended to be used as static imports
Guava Basic Utilities
 String Utilities
 Preconditions
 Objects Helper
 Avoiding Nulls
 StopWatch
Object common methods
Objects.equal(Object, Object)
Objects.hashCode(Object...)
Objects.toStringHelper(Object)
Objects.firstNonNull(T, T)
equal(…) & hashCode(…)
public class Person {
private final String name, nickname;
private final Movie favoriteMovie;
@Override
public boolean equals(Object object) {
if (object instanceof Person) {
Person that = (Person) object;
return Objects.equal(this.name, that.name)
&& Objects.equal(this.nickname, that.nickname)
&& Objects.equal(this.favoriteMovie, that.favoriteMovie);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(name, nickname, favoriteMovie);
}
toStringHelper(…) & firstNonNull(T, T)
@Override
public String toString() {
// speakers is @Nullable!
return Objects.toStringHelper(this)
.add("conference", name)
.add(“location", location)
.add("speakers", speakers)
.omitNullValues().toString();
}
>> "Person{name=JeeConf, location=Kiev}“
// w/o omitNullValues()
>> "Person{name=JeeConf, location=Kiev, speakers=null}“
public String preferredLocation() {
return Objects.firstNonNull(location, name);
}
Guava Basic Utilities
 String Utilities
 Preconditions
 Objects Helper
 Avoiding Nulls
 StopWatch
Null is ambiguous
if (x != null && x.someM() != null && ..) {
// some code…
}
Problem with Null
No entry? Or entry exists but the nickname is unlisted?
Person person = personService.findByNickname(“Andy");
if (person == null) {
// what does this mean?
}
Problem with Null
No entry? Or entry exists but the nickname is unlisted?
The value in the map is null, or the value is not in the
map. Null can mean failure, can mean success, can
mean almost anything.
Person person = personService.findByNickname(“Andy");
if (person == null) {
// what does this mean?
}
Map.get(key)
Optional<T> vs. null
 null is "hidden", Optional is ”explicit”
 An immutable wrapper that is either:
 present: contains a non-null reference
 absent: contains nothing
 Note that it never "contains null"
 Possible uses:
 return type
 “a T that must be present"
 "a T that might be absent"
 distinguish between
 "unknown" (for example, not present in a map)
 "known to have no value" (present in the map, with value
Optional.absent())
 wrap nullable references for storage in a collection that does
not support null
Optional<T>
// Make optional of given type
Optional<String> possible = Optional.of(“Ido”);
Optional<String> value = Optional.fromNullable(str);
if (value.isPresent()) {
// ...
}
// returns true if nonNull
possible.isPresent();
// returns this possible value or default
possible.or(“Nick”);
// returns Ido
possible.get();
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
For null-unfriendly collections
 Many collections, including the JDK's Queue and
ConcurrentMap implementations, don't allow null
elements.
 Queue<Optional<Foo>> is a simple and natural
solution!
Others… Strings
 Methods are primarily for interfacing with
unpleasant APIs that equate null strings and empty
strings:
Strings.emptyToNull(String)
Strings.isNullOrEmpty(String)
Strings.nullToEmpty(String)
https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained
Guava Basic Utilities
 String Utilities
 Preconditions
 Objects Helper
 Avoiding Nulls
 StopWatch
StopWatch
 Class for measuring elapsed time
 Prefer StopWatch over System.nanoTime()
 Don't use System.currentTimeMillis()!
 Provides methods that automatically calculate time
between start() and stop() execution
StopWatch
public void measureElapsedTime(Collection<String> input) {
Stopwatch stopwatch = new Stopwatch().start();
doSomeOperation(input);
long nanos = stopwatch.elapsed(TimeUnit.NANOSECONDS);
}
StopWatch Pros
 StopWatch uses nanoTime() but exposes only relative
timings, a meaningless absolute value
 Alternate time sources can be substituted using Ticker
(read() returns nanoseconds)
 Can be easily mocked with custom passing time provider
 Returns counted time using different units
 toString() gives human readable format
Functional Concepts brought to Java
 Many things in Guava are inspired by functional
concepts from other programming languages
 In Java can only be approximated through awkward
and verbose use of anonymous classes
 Expected to change in Java 8
 Guava is currently aimed at users of Java 5 and
above
Core concepts
 Key functional concepts Guava uses:
Core concepts
 Key functional concepts Guava uses:
 Function<F, T> == F => T
=> to transform a collection
public interface Function<F, T> {
@Nullable T apply(@Nullable F input);
}
Core concepts
 Key functional concepts Guava uses:
 Function<F, T> == F => T
=> to transform a collection
 Predicate<T> == T => Boolean
=> filter out a collection
public interface Function<F, T> {
@Nullable T apply(@Nullable F input);
}
public interface Predicate<T> {
boolean apply(@Nullable T input);
}
Function<F,T> usage
Iterables.transform()
FluentIterable.transform()
Iterators.transform()
Collections2.transform()
Lists.transform()
Maps, Multimaps … etc.
 Main usage with transform()
 Tools to manipulate collections using Function:
FluentIterable API
 Chaining methods (return FluentIterable<T>)
 filter(Predicate)
 transform(Function)
 skip(int), limit(int)
 cycle()
 Query methods (return boolean)
 allMatch(Predicate), anyMatch(Predicate)
 contains(Object)
 isEmpty()
 Extraction methods (return Optional<T>)
 first(), last(), firstMatch(Predicate), get(int)
 Conversion methods (return a copied Collection<T>)
 toList(), toSet(), toSortedSet(), toArray()
Function <F,T>
 Java 7 doesn't have lambda expressions, but Guava
helps us out (a bit) with Function
public void demo(Collection<String> input) {
Function<String, String> toUpperCase =
new Function<String, String>() {
@Override
public String apply(String string) {
return string.toUpperCase();
}
};
Collection<String> transformed =
Collections2.transform(input, toUpperCase);
}
Predicate<T> usage
 Predicate checks if condition is met for passed object
 Tools to manipulate collections using Predicate:
FluentIterables.filter()
Iterables.filter()
Iterators.filter()
Collections2.filter()
Sets.filter()
Maps, MultiMaps, … etc.
Predicate <T>
 Quite similar to Function but does NOT extend it 
Predicate<User> onlyAwesome = new Predicate<User>() {
@Override
public boolean apply(User in) {
return Optional.fromNullable(in)
.or(User.NOT_AWESOME).isAwesome();
}
};
Predicate <T>
 Let's use it on a collection:
Iterable<User> users = getMixedUsers();
// find all awesome users
Iterable<User> onlyAwesomeUsers = Iterables.filter(users, onlyAwesome);
// find one (first) awesome user
User awesomeUser = Iterables.find(users, onlyAwesome);
// or better
Optional<User> awesomeOrAbsent = Iterables.tryFind(users, onlyAwesome);
Putting it together
private Iterable<Integer> puttingItTogether(Iterable<Integer> numbers)
{
FluentIterable<Integer> squaresOfEvens =
FluentIterable.from(numbers)
.filter(new Predicate<Integer>() {
@Override
public boolean apply(Integer input) {
checkNotNull(input, "nulls are not allowed here!");
return input % 2 == 0;
}}).transform(new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
checkNotNull(input, "nulls are not allowed here!");
return input * input;
}
});
return squaresOfEvens;
}
… Or
List<Integer> squaresOfEvens = Lists.newArrayList();
for (Integer number : givenNumbers) {
if (number % 2 == 0) {
squaresOfEvens.add(number * number);
}
}
>> [ 4, 16, 36, 64, 100 ]
… Moral
List<Integer> squaresOfEvens = Lists.newArrayList();
for (Integer number : givenNumbers) {
if (number % 2 == 0) {
squaresOfEvens.add(number * number);
}
}
>> [ 4, 16, 36, 64, 100 ]
 Just be careful!!
 Functional style can be great but it's not
automatically the better way to go.
Java Caching
Java Caching with Guava
 Guava has a powerful on-heap key→value cache
 Thread-safe implementation
 More or less internally similar to ConcurrentMap +
automatic eviction
 No explicit support for distributed caching
Types of Caches
 Provides two types of caches:
 LoadingCache - knows how to load entries when
a cache miss occurs
 LoadingCache.get(key) returns the value associated with
key, loading it first if necessary
 Cache - does not automatically load entries
 We're going to focus on the loading case here; it's
usually what you want
Caches (example)
CacheLoader<String, Graph> loader =
new CacheLoader<String, Graph>() {
@Override
public Graph load(String key) {
return createExpensiveGraph(key);
}
};
LoadingCache<String, Graph> cache =
CacheBuilder.newBuilder().build(loader);
CacheBuilder
 The CacheBuilder has next properties:
 Cache size
 Time to expire entries after last access
 Time based expiration of entries after being updated
 Use of weak or soft references for keys/values
 Setting RemovalListener that can receive events once
an entry is removed fro the cache.
 Concurrency level for update operations (defaults to 4)
 Enable recording caching stats
CacheBuilder (example)
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterAccess(10, TimeUnit.SECONDS)
.recordStats()
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
return key.toUpperCase();
}
});
Concurrency
 Cache instances are internally implemented very
similar to ConcurrentHashMap (thus thread-safe)
 CacheLoader.load will be invoked a single time for
each key, regardless of the number of requesting
threads
 The result will be returned to all requesting
threads and inserted into the cache using the
equivalent of putIfAbsent
Cache Eviction
 By size
 .maximumSize(long)
 By custom weight:
 .weigher(Weigher)
 .maximumWeight(long)
 By time:
 .expireAfterAccess(long, TimeUnit)
 .expireAfterWrite(long, TimeUnit)
Cache Eviction (cont.)
 Reference-based eviction:
 .weakKeys()
 .weakValues()
 .softValues()
 Explicit:
 .invalidate(key)
 .invalidateAll(keys)
 .invalidateAll()
Checked Exceptions
 What if loading causes a checked exception?
CacheLoader<String, String> checkedLoader =
new CacheLoader<String, String>() {
@Override
public String load(String key) throws IOException {
return loadFromDisk(key);
}
};
Checked Exceptions (cont.)
LoadingCache<String, String> cache =
CacheBuilder.newBuilder().build(checkedLoader);
try {
cache.get(key);
} catch (ExecutionException e) {
// ensure stack trace is for this thread
throw new IOException(e.getCause());
}
Cache Stats
 hitCount – number of times Cache returned the
cached value
 missCount – number of times Cache returned
uncached value
 loadSuccessCount – number of times Cache
loaded new value successfully
Cache Stats (example)
LoadingCache<String, String> cache =
CacheBuilder.newBuilder()
.recordStats().build(checkedLoader);
// cumulative stats since cache creation
CacheStats stats = cache.stats();
CacheStats{
hitCount=4, missCount=3, loadSuccessCount=3,
loadExceptionCount=0, totalLoadTime=676064, evictionCount=0
}
…Collections
MultiSet<E>
 Implements Collection<E>
List: [a, c, b, b, c, a, a, b]
Set: [a, c, b]
Multiset: [a, a, a, c, c, b, b, b]
MultiSet<E>
 Implements Collection<E>
List: [a, c, b, b, c, a, a, b]
Set: [a, c, b]
Multiset: [a, a, a, c, c, b, b, b]
 So a Multiset<E> implementation only needs to
store one occurrence of each element, plus a count!
[a x 3, c x 2, b x 3]
MultiSet<E>
 Add multiple instances of a given element
 Counts how many occurrences exist
 Similar to a Map<E, Integer>, but...
 only positive counts
 size() returns total # of items, not # keys
 count() for a non-existent key is 0
 iterator() goes over each element
 Usage: i.e. Track frequencies of elements, e.g. "word
counting"
MultiSet<E> Implementations
 HashMultiset
 TreeMultiset
 LinkedHashMultiset
 ConcurrentHashMultiset
 ImmutableMultiset
Tired of this?
Map<String, List<String>>
Tired of this?
Map<String, List<String>>
{a=1, a=2, b=3, c=4, c=5, c=6}
Try …
MultiMap<K, V>
 Like Map (key-value pairs), but may have duplicates
 The values related to a single key can be viewed as a
collection (set or list)
 Similar to a Map<K, Collection<V>>, but...
 get() never returns null (returns an empty collection)
 containsKey() is true only if 1 or more values exist
 entries() returns all entries for all keys
 size() returns total number of entries, not keys
 asMap() to view it as a Map<K, Collection<V>>
MultiMap<K, V>
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" ]
MultiMap Implementations
 ArrayListMultimap
 HashMultimap
 LinkedListMultima
 LinkedHashMultimap
 TreeMultimap
 ImmutableListMultimap
 ImmutableSetMultimap
BiMap<K1, K2>
 Bi-directional Map
 Both keys and values are unique
 Can view the inverse map with inverse()
 Use instead of maintaining two separate
maps:
 Map<K1, K2>
 Map<K2, K1>
Static utilities
 In classes with name ending with an s
 Lists
 Maps
 Multimaps
 Multisets
 Sets
 SortedMaps
 Tables
 Iterators
 Iterables
 Collections2
Static factories methods
 Rather than typing
 you type
Map<String, Class<? extends Handler>> m =
new HashMap<String, Class<? extends Handler>>();
Map<String, Class<? extends Handler>> m2 = Maps.newHashMap();
Guava Alternatives
 Should you use Guava or Apache Commons?
 We may be biased, so consult this question on Stack
Overflow:
 http://tinyurl.com/guava-vs-apache
 The large number of upvotes for the top answers
shows a pretty strong community consensus
Need help with a problem?
 Post to Stack Overflow! Use the "guava" tag
 Report a defect, request an enhancement?
 http://code.google.com/p/guava-libraries/issues/list
 Start an email discussion?
 Send to guava-discuss@googlegroups.com
 General discussion takes place on
 http://groups.google.com/group/guava-discuss
 The Guava team is generally highly active in all of
these areas
Time to Play
What to Remember 
 Functional flavor of collection handling
 CharMatcher / Splitter / Joiner
 Avoid null  where possible
 Ease of Preconditions
 Caching
 Multimap / Multiset / Bimap
Q&A
http://www.flickr.com/photos/wwworks/4759535950/sizes/o/in/photostream/
References
 http://code.google.com/p/guava-libraries/
 http://code.google.com/p/guava-
libraries/downloads/list

More Related Content

What's hot

Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to knowTomasz Dziurko
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistAnton Arhipov
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingAnton Arhipov
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleAnton Arhipov
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsBaruch Sadogursky
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
Groovy 1.8の新機能について
Groovy 1.8の新機能についてGroovy 1.8の新機能について
Groovy 1.8の新機能についてUehara Junji
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8James Brown
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorFedor Lavrentyev
 
0003 es5 핵심 정리
0003 es5 핵심 정리0003 es5 핵심 정리
0003 es5 핵심 정리욱래 김
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/HibernateSunghyouk Bae
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
An Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersAn Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersFITC
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...Haris Mahmood
 

What's hot (20)

Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 
Groovy 1.8の新機能について
Groovy 1.8の新機能についてGroovy 1.8の新機能について
Groovy 1.8の新機能について
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
 
Java Annotations and Pre-processing
Java  Annotations and Pre-processingJava  Annotations and Pre-processing
Java Annotations and Pre-processing
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
Akka tips
Akka tipsAkka tips
Akka tips
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
 
0003 es5 핵심 정리
0003 es5 핵심 정리0003 es5 핵심 정리
0003 es5 핵심 정리
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
An Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersAn Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End Developers
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
 

Viewers also liked

Thrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased ComparisonThrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased ComparisonIgor Anishchenko
 
cache2k, Java Caching, Turbo Charged, FOSDEM 2015
cache2k, Java Caching, Turbo Charged, FOSDEM 2015cache2k, Java Caching, Turbo Charged, FOSDEM 2015
cache2k, Java Caching, Turbo Charged, FOSDEM 2015cruftex
 
Overview of PaaS: Java experience
Overview of PaaS: Java experienceOverview of PaaS: Java experience
Overview of PaaS: Java experienceIgor Anishchenko
 
Malunggay And Guava Leaves Decoction
Malunggay And Guava Leaves DecoctionMalunggay And Guava Leaves Decoction
Malunggay And Guava Leaves DecoctionJack Frost
 
Meadow orchrad in_guava
Meadow orchrad in_guavaMeadow orchrad in_guava
Meadow orchrad in_guavaMomin Saeed
 
From cache to in-memory data grid. Introduction to Hazelcast.
From cache to in-memory data grid. Introduction to Hazelcast.From cache to in-memory data grid. Introduction to Hazelcast.
From cache to in-memory data grid. Introduction to Hazelcast.Taras Matyashovsky
 
The thesis and its parts
The thesis and its partsThe thesis and its parts
The thesis and its partsDraizelle Sexon
 
Writing thesis chapters 1-3 guidelines
Writing thesis chapters 1-3 guidelinesWriting thesis chapters 1-3 guidelines
Writing thesis chapters 1-3 guidelinespoleyseugenio
 

Viewers also liked (11)

Thrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased ComparisonThrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased Comparison
 
cache2k, Java Caching, Turbo Charged, FOSDEM 2015
cache2k, Java Caching, Turbo Charged, FOSDEM 2015cache2k, Java Caching, Turbo Charged, FOSDEM 2015
cache2k, Java Caching, Turbo Charged, FOSDEM 2015
 
Top 15 Health benefits of guava that you should know
Top 15 Health benefits of guava that you should knowTop 15 Health benefits of guava that you should know
Top 15 Health benefits of guava that you should know
 
Overview of PaaS: Java experience
Overview of PaaS: Java experienceOverview of PaaS: Java experience
Overview of PaaS: Java experience
 
Malunggay And Guava Leaves Decoction
Malunggay And Guava Leaves DecoctionMalunggay And Guava Leaves Decoction
Malunggay And Guava Leaves Decoction
 
Meadow orchrad in_guava
Meadow orchrad in_guavaMeadow orchrad in_guava
Meadow orchrad in_guava
 
Guava
GuavaGuava
Guava
 
Thesis Writing
Thesis WritingThesis Writing
Thesis Writing
 
From cache to in-memory data grid. Introduction to Hazelcast.
From cache to in-memory data grid. Introduction to Hazelcast.From cache to in-memory data grid. Introduction to Hazelcast.
From cache to in-memory data grid. Introduction to Hazelcast.
 
The thesis and its parts
The thesis and its partsThe thesis and its parts
The thesis and its parts
 
Writing thesis chapters 1-3 guidelines
Writing thesis chapters 1-3 guidelinesWriting thesis chapters 1-3 guidelines
Writing thesis chapters 1-3 guidelines
 

Similar to Clean code with google guava jee conf

Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Codemotion
 
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super PowersJDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super PowersPROIDEA
 
Javascript Experiment
Javascript ExperimentJavascript Experiment
Javascript Experimentwgamboa
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leetjohndaviddalton
 
Automated code audits
Automated code auditsAutomated code audits
Automated code auditsDamien Seguy
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018 Codemotion
 
Java Intro
Java IntroJava Intro
Java Introbackdoor
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scalaparag978978
 
jQuery - Introdução
jQuery - IntroduçãojQuery - Introdução
jQuery - IntroduçãoGustavo Dutra
 
JQuery do dia-a-dia Gustavo Dutra
JQuery do dia-a-dia Gustavo DutraJQuery do dia-a-dia Gustavo Dutra
JQuery do dia-a-dia Gustavo DutraTchelinux
 
Soundreader.classpathSoundreader.project Soundre.docx
Soundreader.classpathSoundreader.project  Soundre.docxSoundreader.classpathSoundreader.project  Soundre.docx
Soundreader.classpathSoundreader.project Soundre.docxwhitneyleman54422
 

Similar to Clean code with google guava jee conf (20)

Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
 
Lazy java
Lazy javaLazy java
Lazy java
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super PowersJDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
 
Javascript Experiment
Javascript ExperimentJavascript Experiment
Javascript Experiment
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
Automated code audits
Automated code auditsAutomated code audits
Automated code audits
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Java
JavaJava
Java
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
 
Java Intro
Java IntroJava Intro
Java Intro
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
jQuery - Introdução
jQuery - IntroduçãojQuery - Introdução
jQuery - Introdução
 
JQuery do dia-a-dia Gustavo Dutra
JQuery do dia-a-dia Gustavo DutraJQuery do dia-a-dia Gustavo Dutra
JQuery do dia-a-dia Gustavo Dutra
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Soundreader.classpathSoundreader.project Soundre.docx
Soundreader.classpathSoundreader.project  Soundre.docxSoundreader.classpathSoundreader.project  Soundre.docx
Soundreader.classpathSoundreader.project Soundre.docx
 

Recently uploaded

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Recently uploaded (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Clean code with google guava jee conf

  • 1.
  • 5.
  • 6.
  • 7.
  • 8. What is Google Guava? annotations basic utilities collections concurrency comparison strings primitives ranges functional idioms I/o caching hashing event bus math reflection net/http
  • 9. What in this presentation? annotations basic utilities collections concurrency comparison strings primitives ranges functional idioms I/O caching hashing event bus math reflection net/http
  • 10.
  • 11.
  • 12.
  • 13. Why Guava?  The goal is for you to write less code ...  Make code more readable, cleaner and simpler  Helps developers to focus on business logic rather than writing java utilities  Saves time, resources and improve productivity  Popular API and active development  Mainstream  Basically... a painkiller and natural extension for Java
  • 14.
  • 16. ref. Effective Java Item 47, "Know and use the libraries“
  • 17.
  • 18. Guava Releases  About every 3 months, with significant new functionality and fixes  Release 14.0.1 was released on March 15, 2013  All releases are either major or patch releases  Never minor
  • 19.
  • 20.
  • 23.
  • 24. Guava Basic Utilities  String Utilities  Preconditions  Objects Helper  Avoiding Nulls  StopWatch
  • 25. String Utilities  Joiner  Splitter  CharMatcher
  • 26. Joining Strings  Who here has ever written this utility? public class StringUtil { public static String join( String separator, Iterable<String> pieces) { // any of ~5 common implementations goes here } }
  • 27. Joining Strings  Converts collections into single String object  Joining an Iterable, Iterator, varargs/array  Return a String, or append to an Appendable  Throws a NPE on null objects, unless:  .skipNulls()  .useForNull(String)  It also works with Maps  We could be looking at 18 to 48 different methods
  • 28. Joining Strings (cont.) List<String> fruits = Arrays.asList( "apple", null, "orange", null, null, "guava"); String joined = Joiner.on(", ").skipNulls().join(fruits); >> "apple, orange, guava"
  • 29. Joining Strings (cont.) List<String> fruits = Arrays.asList( "apple", null, "orange", null, null, "guava"); String joined = Joiner.on(", ").skipNulls().join(fruits); >> "apple, orange, guava" String joined = Joiner.on(",").useForNull("banana").join(fruits); >> "apple, banana, orange, banana, banana, guava"
  • 30. Splitting Strings  Working in the opposite direction than Joiner  Allows to split String into collection of elements  String.split() on steroids   A better, more intuitive String.split()  Doesn't silently discard trailing separators  Handles empty pieces predictably
  • 31. Splitter String input = ",, ,apple, orange ,,, banana,, ,guava, ,,"; Iterable<String> split = Splitter.on(',') .omitEmptyStrings() .trimResults() .split(input); >> [ "apple", "orange", "banana", "guava" ]  The default behavior is simplistic  If you want extra features, ask for them!
  • 32. Splitter String input = ",, ,apple, orange ,,, banana,, ,guava, ,,"; Iterable<String> split = Splitter.on(',') .omitEmptyStrings() .trimResults() .split(input); >> [ "apple", "orange", "banana", "guava" ]  The default behavior is simplistic  If you want extra features, ask for them!  By default, assumes nothing about whitespace  These classes use what Googlers (tentatively) call the "Utility Object pattern."
  • 33. Splitter more… Splitter.onPattern("d+").split("Java3Scala4Haskell0Brainfuck5Kotlin"); >> [ "Java ", "Scala", "Haskell", "Brainfuck", "Kotlin" ] Splitter.on(CharMatcher.inRange('3','5')) .split("Java3Scala4Haskell0Brainfuck5Kotlin"); >> [ "Java", "Scala", "Haskell0Brainfuck", "Kotlin" ]  Split using regular expression  Split using CharMatcher
  • 34. CharMatcher  CharMatcher provides many text processing methods based on “matching character” notation  Separates "configuration" from "processing"  CharMatcher represents two notions:  What constitutes a matching character?  What to do with those matching characters?  Can also be used to "filter" chars
  • 35. CharMatcher (cont.)  Allows to check if a sequence of characters satisfies given condition: WHITESPACE, ASCII, ANY, DIGIT (many pre-defined sets) is('x') isNot('_') oneOf("aeiou") inRange('a', 'z') .or (inRange('A', 'Z')).negate()
  • 36. All that you can do... CharMatcher  Provides methods to modify char sequences: boolean matchesAllOf(CharSequence) boolean matchesAnyOf(CharSequence) boolean matchesNoneOf(CharSequence) int indexIn(CharSequence, int) int lastIndexIn(CharSequence, int) int countIn(CharSequence) String removeFrom(CharSequence) String retainFrom(CharSequence) String trimFrom(CharSequence) String trimLeadingFrom(CharSequence) String trimTrailingFrom(CharSequence) String collapseFrom(CharSequence, char) String trimAndCollapseFrom(CharSequence, char) String replaceFrom(CharSequence, char)
  • 37. CharMatcher (example) CharMatcher matcher = CharMatcher.DIGIT .or(CharMatcher.inRange('a', 'z') .or(CharMatcher.inRange('A', 'Z'))); if (matcher.matchesAllOf("this1will2match3")) { // ... }
  • 38. CharMatcher (example) // eliminate all characters that aren't digits or lowercase String lowerAndDigit = CharMatcher.DIGIT .or(CharMatcher.JAVA_LOWER_CASE) .retainFrom(input); CharMatcher matcher = CharMatcher.DIGIT .or(CharMatcher.inRange('a', 'z') .or(CharMatcher.inRange('A', 'Z'))); if (matcher.matchesAllOf("this1will2match3")) { // ... }
  • 39. CharMatcher (example) String pass = “$$$ secret passcode $$$"; String result = CharMatcher.is(“$”).trimFrom(pass); >> “ secret password " trimLeadingFrom(), trimTrailingFrom() or trimAndCollapseFrom()
  • 40. Guava Basic Utilities  String Utilities  Preconditions  Objects Helper  Avoiding Nulls  StopWatch
  • 41. checkState(boolean)  Throws IllegalStateException if false  Used to check object state if (state != State.PLAYABLE) { throw new IllegalStateException( "Can't play movie; state is " + state); }
  • 42. checkState(boolean)  Throws IllegalStateException if false  Used to check object state … or… if (state != State.PLAYABLE) { throw new IllegalStateException( "Can't play movie; state is " + state); } Preconditions.checkState(state == State.PLAYABLE, "Can't play movie; state is %s", state); (what's the difference? none!)
  • 43. checkNotNull(T)  Throws NullPointerException if null  Returns the value. Can be used inline. public Car(Engine engine) { this.engine = Preconditions.checkNotNull(engine); }
  • 44. checkNotNull(T)  Throws NullPointerException if null  Returns the value. Can be used inline. . . . with using static import . . . public Car(Engine engine) { this.engine = Preconditions.checkNotNull(engine); } public Car(Engine engine) { this.engine = checkNotNull(engine, “engine cannot be null”); }
  • 45. checkArgument(boolean)  Throws IllegalArgumentException if false  Used to validate method arguments public void drive(double speed) { Preconditions.checkArgument(speed > 0.0, "Speed (%s) must be positive", speed); }
  • 46. Why Preconditions?  Defensive coding   Useful for validation  Each method has three variants:  No extra arguments  An extra object for error message  An extra String & Objects. String.format like but only allows %s  Recommended to be used as static imports
  • 47. Guava Basic Utilities  String Utilities  Preconditions  Objects Helper  Avoiding Nulls  StopWatch
  • 48. Object common methods Objects.equal(Object, Object) Objects.hashCode(Object...) Objects.toStringHelper(Object) Objects.firstNonNull(T, T)
  • 49. equal(…) & hashCode(…) public class Person { private final String name, nickname; private final Movie favoriteMovie; @Override public boolean equals(Object object) { if (object instanceof Person) { Person that = (Person) object; return Objects.equal(this.name, that.name) && Objects.equal(this.nickname, that.nickname) && Objects.equal(this.favoriteMovie, that.favoriteMovie); } return false; } @Override public int hashCode() { return Objects.hashCode(name, nickname, favoriteMovie); }
  • 50. toStringHelper(…) & firstNonNull(T, T) @Override public String toString() { // speakers is @Nullable! return Objects.toStringHelper(this) .add("conference", name) .add(“location", location) .add("speakers", speakers) .omitNullValues().toString(); } >> "Person{name=JeeConf, location=Kiev}“ // w/o omitNullValues() >> "Person{name=JeeConf, location=Kiev, speakers=null}“ public String preferredLocation() { return Objects.firstNonNull(location, name); }
  • 51. Guava Basic Utilities  String Utilities  Preconditions  Objects Helper  Avoiding Nulls  StopWatch
  • 52. Null is ambiguous if (x != null && x.someM() != null && ..) { // some code… }
  • 53. Problem with Null No entry? Or entry exists but the nickname is unlisted? Person person = personService.findByNickname(“Andy"); if (person == null) { // what does this mean? }
  • 54. Problem with Null No entry? Or entry exists but the nickname is unlisted? The value in the map is null, or the value is not in the map. Null can mean failure, can mean success, can mean almost anything. Person person = personService.findByNickname(“Andy"); if (person == null) { // what does this mean? } Map.get(key)
  • 55.
  • 56. Optional<T> vs. null  null is "hidden", Optional is ”explicit”  An immutable wrapper that is either:  present: contains a non-null reference  absent: contains nothing  Note that it never "contains null"  Possible uses:  return type  “a T that must be present"  "a T that might be absent"  distinguish between  "unknown" (for example, not present in a map)  "known to have no value" (present in the map, with value Optional.absent())  wrap nullable references for storage in a collection that does not support null
  • 57. Optional<T> // Make optional of given type Optional<String> possible = Optional.of(“Ido”); Optional<String> value = Optional.fromNullable(str); if (value.isPresent()) { // ... } // returns true if nonNull possible.isPresent(); // returns this possible value or default possible.or(“Nick”); // returns Ido possible.get();
  • 58. 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
  • 59. For null-unfriendly collections  Many collections, including the JDK's Queue and ConcurrentMap implementations, don't allow null elements.  Queue<Optional<Foo>> is a simple and natural solution!
  • 60. Others… Strings  Methods are primarily for interfacing with unpleasant APIs that equate null strings and empty strings: Strings.emptyToNull(String) Strings.isNullOrEmpty(String) Strings.nullToEmpty(String)
  • 62. Guava Basic Utilities  String Utilities  Preconditions  Objects Helper  Avoiding Nulls  StopWatch
  • 63. StopWatch  Class for measuring elapsed time  Prefer StopWatch over System.nanoTime()  Don't use System.currentTimeMillis()!  Provides methods that automatically calculate time between start() and stop() execution
  • 64. StopWatch public void measureElapsedTime(Collection<String> input) { Stopwatch stopwatch = new Stopwatch().start(); doSomeOperation(input); long nanos = stopwatch.elapsed(TimeUnit.NANOSECONDS); }
  • 65. StopWatch Pros  StopWatch uses nanoTime() but exposes only relative timings, a meaningless absolute value  Alternate time sources can be substituted using Ticker (read() returns nanoseconds)  Can be easily mocked with custom passing time provider  Returns counted time using different units  toString() gives human readable format
  • 66. Functional Concepts brought to Java  Many things in Guava are inspired by functional concepts from other programming languages  In Java can only be approximated through awkward and verbose use of anonymous classes  Expected to change in Java 8  Guava is currently aimed at users of Java 5 and above
  • 67. Core concepts  Key functional concepts Guava uses:
  • 68. Core concepts  Key functional concepts Guava uses:  Function<F, T> == F => T => to transform a collection public interface Function<F, T> { @Nullable T apply(@Nullable F input); }
  • 69. Core concepts  Key functional concepts Guava uses:  Function<F, T> == F => T => to transform a collection  Predicate<T> == T => Boolean => filter out a collection public interface Function<F, T> { @Nullable T apply(@Nullable F input); } public interface Predicate<T> { boolean apply(@Nullable T input); }
  • 71. FluentIterable API  Chaining methods (return FluentIterable<T>)  filter(Predicate)  transform(Function)  skip(int), limit(int)  cycle()  Query methods (return boolean)  allMatch(Predicate), anyMatch(Predicate)  contains(Object)  isEmpty()  Extraction methods (return Optional<T>)  first(), last(), firstMatch(Predicate), get(int)  Conversion methods (return a copied Collection<T>)  toList(), toSet(), toSortedSet(), toArray()
  • 72. Function <F,T>  Java 7 doesn't have lambda expressions, but Guava helps us out (a bit) with Function public void demo(Collection<String> input) { Function<String, String> toUpperCase = new Function<String, String>() { @Override public String apply(String string) { return string.toUpperCase(); } }; Collection<String> transformed = Collections2.transform(input, toUpperCase); }
  • 73. Predicate<T> usage  Predicate checks if condition is met for passed object  Tools to manipulate collections using Predicate: FluentIterables.filter() Iterables.filter() Iterators.filter() Collections2.filter() Sets.filter() Maps, MultiMaps, … etc.
  • 74. Predicate <T>  Quite similar to Function but does NOT extend it  Predicate<User> onlyAwesome = new Predicate<User>() { @Override public boolean apply(User in) { return Optional.fromNullable(in) .or(User.NOT_AWESOME).isAwesome(); } };
  • 75. Predicate <T>  Let's use it on a collection: Iterable<User> users = getMixedUsers(); // find all awesome users Iterable<User> onlyAwesomeUsers = Iterables.filter(users, onlyAwesome); // find one (first) awesome user User awesomeUser = Iterables.find(users, onlyAwesome); // or better Optional<User> awesomeOrAbsent = Iterables.tryFind(users, onlyAwesome);
  • 76. Putting it together private Iterable<Integer> puttingItTogether(Iterable<Integer> numbers) { FluentIterable<Integer> squaresOfEvens = FluentIterable.from(numbers) .filter(new Predicate<Integer>() { @Override public boolean apply(Integer input) { checkNotNull(input, "nulls are not allowed here!"); return input % 2 == 0; }}).transform(new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { checkNotNull(input, "nulls are not allowed here!"); return input * input; } }); return squaresOfEvens; }
  • 77. … Or List<Integer> squaresOfEvens = Lists.newArrayList(); for (Integer number : givenNumbers) { if (number % 2 == 0) { squaresOfEvens.add(number * number); } } >> [ 4, 16, 36, 64, 100 ]
  • 78. … Moral List<Integer> squaresOfEvens = Lists.newArrayList(); for (Integer number : givenNumbers) { if (number % 2 == 0) { squaresOfEvens.add(number * number); } } >> [ 4, 16, 36, 64, 100 ]  Just be careful!!  Functional style can be great but it's not automatically the better way to go.
  • 79.
  • 81. Java Caching with Guava  Guava has a powerful on-heap key→value cache  Thread-safe implementation  More or less internally similar to ConcurrentMap + automatic eviction  No explicit support for distributed caching
  • 82. Types of Caches  Provides two types of caches:  LoadingCache - knows how to load entries when a cache miss occurs  LoadingCache.get(key) returns the value associated with key, loading it first if necessary  Cache - does not automatically load entries  We're going to focus on the loading case here; it's usually what you want
  • 83. Caches (example) CacheLoader<String, Graph> loader = new CacheLoader<String, Graph>() { @Override public Graph load(String key) { return createExpensiveGraph(key); } }; LoadingCache<String, Graph> cache = CacheBuilder.newBuilder().build(loader);
  • 84. CacheBuilder  The CacheBuilder has next properties:  Cache size  Time to expire entries after last access  Time based expiration of entries after being updated  Use of weak or soft references for keys/values  Setting RemovalListener that can receive events once an entry is removed fro the cache.  Concurrency level for update operations (defaults to 4)  Enable recording caching stats
  • 85. CacheBuilder (example) LoadingCache<String, String> cache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterAccess(10, TimeUnit.SECONDS) .recordStats() .build(new CacheLoader<String, String>() { @Override public String load(String key) throws Exception { return key.toUpperCase(); } });
  • 86. Concurrency  Cache instances are internally implemented very similar to ConcurrentHashMap (thus thread-safe)  CacheLoader.load will be invoked a single time for each key, regardless of the number of requesting threads  The result will be returned to all requesting threads and inserted into the cache using the equivalent of putIfAbsent
  • 87. Cache Eviction  By size  .maximumSize(long)  By custom weight:  .weigher(Weigher)  .maximumWeight(long)  By time:  .expireAfterAccess(long, TimeUnit)  .expireAfterWrite(long, TimeUnit)
  • 88. Cache Eviction (cont.)  Reference-based eviction:  .weakKeys()  .weakValues()  .softValues()  Explicit:  .invalidate(key)  .invalidateAll(keys)  .invalidateAll()
  • 89. Checked Exceptions  What if loading causes a checked exception? CacheLoader<String, String> checkedLoader = new CacheLoader<String, String>() { @Override public String load(String key) throws IOException { return loadFromDisk(key); } };
  • 90. Checked Exceptions (cont.) LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(checkedLoader); try { cache.get(key); } catch (ExecutionException e) { // ensure stack trace is for this thread throw new IOException(e.getCause()); }
  • 91. Cache Stats  hitCount – number of times Cache returned the cached value  missCount – number of times Cache returned uncached value  loadSuccessCount – number of times Cache loaded new value successfully
  • 92. Cache Stats (example) LoadingCache<String, String> cache = CacheBuilder.newBuilder() .recordStats().build(checkedLoader); // cumulative stats since cache creation CacheStats stats = cache.stats(); CacheStats{ hitCount=4, missCount=3, loadSuccessCount=3, loadExceptionCount=0, totalLoadTime=676064, evictionCount=0 }
  • 94. MultiSet<E>  Implements Collection<E> List: [a, c, b, b, c, a, a, b] Set: [a, c, b] Multiset: [a, a, a, c, c, b, b, b]
  • 95. MultiSet<E>  Implements Collection<E> List: [a, c, b, b, c, a, a, b] Set: [a, c, b] Multiset: [a, a, a, c, c, b, b, b]  So a Multiset<E> implementation only needs to store one occurrence of each element, plus a count! [a x 3, c x 2, b x 3]
  • 96. MultiSet<E>  Add multiple instances of a given element  Counts how many occurrences exist  Similar to a Map<E, Integer>, but...  only positive counts  size() returns total # of items, not # keys  count() for a non-existent key is 0  iterator() goes over each element  Usage: i.e. Track frequencies of elements, e.g. "word counting"
  • 97. MultiSet<E> Implementations  HashMultiset  TreeMultiset  LinkedHashMultiset  ConcurrentHashMultiset  ImmutableMultiset
  • 98. Tired of this? Map<String, List<String>>
  • 99. Tired of this? Map<String, List<String>> {a=1, a=2, b=3, c=4, c=5, c=6}
  • 101. MultiMap<K, V>  Like Map (key-value pairs), but may have duplicates  The values related to a single key can be viewed as a collection (set or list)  Similar to a Map<K, Collection<V>>, but...  get() never returns null (returns an empty collection)  containsKey() is true only if 1 or more values exist  entries() returns all entries for all keys  size() returns total number of entries, not keys  asMap() to view it as a Map<K, Collection<V>>
  • 102. MultiMap<K, V> 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" ]
  • 103. MultiMap Implementations  ArrayListMultimap  HashMultimap  LinkedListMultima  LinkedHashMultimap  TreeMultimap  ImmutableListMultimap  ImmutableSetMultimap
  • 104. BiMap<K1, K2>  Bi-directional Map  Both keys and values are unique  Can view the inverse map with inverse()  Use instead of maintaining two separate maps:  Map<K1, K2>  Map<K2, K1>
  • 105. Static utilities  In classes with name ending with an s  Lists  Maps  Multimaps  Multisets  Sets  SortedMaps  Tables  Iterators  Iterables  Collections2
  • 106. Static factories methods  Rather than typing  you type Map<String, Class<? extends Handler>> m = new HashMap<String, Class<? extends Handler>>(); Map<String, Class<? extends Handler>> m2 = Maps.newHashMap();
  • 107. Guava Alternatives  Should you use Guava or Apache Commons?  We may be biased, so consult this question on Stack Overflow:  http://tinyurl.com/guava-vs-apache  The large number of upvotes for the top answers shows a pretty strong community consensus
  • 108. Need help with a problem?  Post to Stack Overflow! Use the "guava" tag  Report a defect, request an enhancement?  http://code.google.com/p/guava-libraries/issues/list  Start an email discussion?  Send to guava-discuss@googlegroups.com  General discussion takes place on  http://groups.google.com/group/guava-discuss  The Guava team is generally highly active in all of these areas
  • 110.
  • 111. What to Remember   Functional flavor of collection handling  CharMatcher / Splitter / Joiner  Avoid null  where possible  Ease of Preconditions  Caching  Multimap / Multiset / Bimap

Editor's Notes

  1. Sir Charles Antony Richard Hoare
  2. CacheBuilder.weakKeys() stores keys using weak references. This allows entries to be garbage-collected if there are no other (strong or soft) references to the keys. Since garbage collection depends only on identity equality, this causes the whole cache to use identity (==) equality to compare keys, instead of equals().CacheBuilder.weakValues() stores values using weak references. This allows entries to be garbage-collected if there are no other (strong or soft) references to the values. Since garbage collection depends only on identity equality, this causes the whole cache to use identity (==) equality to compare values, instead of equals().CacheBuilder.softValues() wraps values in soft references. Softly referenced objects are garbage-collected in a globally least-recently-used manner, in response to memory demand. Because of the performance implications of using soft references, we generally recommend using the more predictable maximum cache size instead. Use of softValues() will cause values to be compared using identity (==) equality instead of equals().