3. What is Google Guava?
• com.google.common.annotation
• com.google.common.base
• com.google.common.collect
• com.google.common.io
• com.google.common.net
• com.google.common.primitives
• com.google.common.util.concurrent
4. NULL
"Null sucks." - Doug Lea
"I call it my billion-dollar
mistake." - C. A. R. Hoare
Null is ambiguous
if ( x != null && x.someM()!=null
&& ) {}
5. @Test
public void optionalExample() {
Optional<Integer> possible = Optional.of(3);// Make
optional of given type
possible.isPresent(); // returns true if nonNull
possible.or(10); // returns this possible value or
default
possible.get(); // returns 3
}
6.
7. @Test
public void testNeverNullWithoutGuava() {
Integer defaultId = null;
Integer id = theUnknowMan.getId() != null ?
theUnknowMan.getId() : defaultId;
}
@Test(expected = NullPointerException.class)
public void testNeverNullWithGuava() {
Integer defaultId = null;
int id = Objects.firstNonNull(theUnknowMan.getId(),
defaultId);
assertEquals(0, id);
}
8.
9. // all in (expression, format,message)
public void somePreconditions() {
checkNotNull(theUnknowMan.getId()); // Will throw NPE
checkState(!theUnknowMan.isSick()); // Will throw
IllegalStateException
checkArgument(theUnknowMan.getAddress() != null,
"We couldn't find the description for customer with
id %s", theUnknowMan.getId());
}
10. JSR-305 Annotations for software defect detection
@Nullable @NotNull
1.javax.validation.constraints.NotNull - EE6
2.edu.umd.cs.findbugs.annotations.NonNull – Findbugs,
Sonar
3.javax.annotation.Nonnull – JSR-305
4.com.intellij.annotations.NotNull - intelliJIDEA
What to use and when?
12. hashCode() and equals()
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result +
((adress == null) ? 0 :
adress.hashCode());
result = prime * result +
((id == null) ? 0 :
id.hashCode());
result = prime * result +
((name == null) ? 0 :
name.hashCode());
result = prime * result +
((url == null) ? 0 :
url.hashCode());
return result;
}
13. hashCode() and equals()
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result +
((adress == null) ? 0 :
adress.hashCode());
result = prime * result +
((id == null) ? 0 :
id.hashCode());
result = prime * result +
((name == null) ? 0 :
name.hashCode());
result = prime * result +
((url == null) ? 0 :
url.hashCode());
return result;
}
14. The Guava way
Objects.equal("a", "a"); //returns true JDK7
Objects.equal(null, "a"); //returns
false Object.deepEquals(Object a, Object b)
Objects.equal("a", null); //returns Object.equals(Object a, Object b)
false
Objects.equal(null, null); //returns
true
Objects.hashCode(name,adress,url); Objects.hash(name,adress,url);
Objects.toStringHelper(this)
.add("x", 1)
.toString();
15. The Guava way
public int compareTo(Foo that) {
return ComparisonChain.start()
.compare(this.aString, that.aString)
.compare(this.anInt, that.anInt)
.compare(this.anEnum, that.anEnum,
Ordering.natural().nullsLast())
.result();
}
18. Character Matchers
Use a predefined constant (examples)
• CharMatcher.WHITESPACE (tracks Unicode defn.)
• CharMatcher.JAVA_DIGIT
• CharMatcher.ASCII
• CharMatcher.ANY
Use a factory method (examples)
• CharMatcher.is('x')
• CharMatcher.isNot('_')
• CharMatcher.oneOf("aeiou").negate()
• CharMatcher.inRange('a', 'z').or(inRange('A',
'Z'))
19. Character Matchers
String noControl =
CharMatcher.JAVA_ISO_CONTROL.removeFrom(string); // remove
control characters
String theDigits = CharMatcher.DIGIT.retainFrom(string); //
only the digits
String lowerAndDigit =
CharMatcher.or(CharMatcher.JAVA_DIGIT,
CharMatcher.JAVA_LOWER_CASE).retainFrom(string);
// eliminate all characters that aren't digits or
lowercase
21. import
com.google.common.collect.*;
• Immutable Collections
• Multimaps, Multisets, BiMaps… aka Google-
Collections
• Comparator-related utilities
• Stuff similar to Apache commons collections
• Some functional programming support
(filter/transform/etc.)
22. Functions and Predicates
Java 8 will support closures …
Function<String, Integer> lengthFunction = new Function<String, Integer>() {
public Integer apply(String string) {
return string.length();
}
};
Predicate<String> allCaps = new Predicate<String>() {
public boolean apply(String string) {
return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string);
}
};
It is not recommended to overuse this!!!
23. Filter collections
@Test
public void filterAwayNullMapValues() {
SortedMap<String, String> map = new TreeMap<String,
String>();
map.put("1", "one");
map.put("2", "two");
map.put("3", null);
map.put("4", "four");
SortedMap<String, String> filtered =
SortedMaps.filterValues(map, Predicates.notNull());
assertThat(filtered.size(), is(3)); // null entry for
"3" is gone!
}
25. Transform collections
ListMultimap<String, String> firstNameToLastNames;
// maps first names to all last names of people with that
first name
ListMultimap<String, String> firstNameToName =
Multimaps.transformEntries(firstNameToLastNames,
new EntryTransformer<String, String, String> () {
public String transformEntry(String firstName, String
lastName) {
return firstName + " " + lastName;
}
});
29. When to use Guava?
• Temporary collections
• Mutable collections
• String Utils
• Check if (x==null)
• Always ?
30. When to use Guava?
"I could just write that myself." But...
•These things are much easier to mess up than it
seems
•With a library, other people will make your code faster
for You
•When you use a popular library, your code is in the
mainstream
•When you find an improvement to your private
library, how
many people did you help?
Well argued in Effective Java 2e, Item 47.
31. Where can you use it ?
•Java 5.0+ <dependency>
<groupId>com.google.guava</groupId>
• GWT <artifactId>guava</artifactId>
<version>10.0.1</version>
•Android </dependency>