SlideShare a Scribd company logo
1 of 32
Download to read offline
Cleaner code with Guava

     Code samples @ git://github.com/mitemitreski/guava-examples.git




@mitemitreski
08-02-2012
What is Guava?
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
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
          && ) {}
@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
 }
@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);
 }
// 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());
 }
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?
Eclipse support
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;
  }
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;
  }
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();
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();
   }
Common Primitives
Joiner/ Splitter
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'))
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
import com.google.common.cache.*;

    Cache<Integer, Customer> cache =
CacheBuilder.newBuilder()
        .weakKeys()
        .maximumSize(10000)
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .build(new CacheLoader<Integer, Customer>() {

          @Override
          public Customer load(Integer key) throws
Exception {

             return retreveCustomerForKey(key);
         }

       });
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.)
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!!!
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!
  }
Filter collections
                                                           Iterables Signature
Collection type Filter method

                                                           boolean all(Iterable, Predicate)
Iterable       Iterables.filter(Iterable, Predicate)


                                                           boolean any(Iterable, Predicate)
Iterator       Iterators.filter(Iterator, Predicate)


Collection     Collections2.filter(Collection, Predicate)T   find(Iterable, Predicate)


Set            Sets.filter(Set, Predicate)
                                                           removeIf(Iterable, Predicate)
SortedSet      Sets.filter(SortedSet, Predicate)


Map            Maps.filterKeys(Map, Predicate)         Maps.filterValues(Map, Maps.filterEntrie
                                                                              Predicate)



SortedMap      Maps.filterKeys(SortedMap, Predicate)Maps.filterValues(SortedMap, Predicate)
                                                                           Maps.filterEntrie



Multimap       Multimaps.filterKeys(Multimap, Predicate)
                                                    Multimaps.filterValues(Multimap, Predic
                                                                           Multimaps.filterE
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;
    }
  });
Transform collections
Collection type   Transform method

Iterable          Iterables.transform(Iterable, Function)

Iterator          Iterators.transform(Iterator, Function)

Collection        Collections2.transform(Collection, Function)

List              Lists.transform(List, Function)

Map*              Maps.transformValues(Map, Function)       Maps.transformEntries(Map, EntryTransfor

SortedMap*        Maps.transformValues(SortedMap, Function)
                                                         Maps.transformEntries(SortedMap, EntryTr

                                                         Multimaps.transformEntries(Mul
Multimap*         Multimaps.transformValues(Multimap, Function)
                                                         timap, EntryTransformer)

                  Multimaps.transformValues(ListMultimap Multimaps.transformEntries(List
ListMultimap*
                  , Function)                            Multimap, EntryTransformer)

Table             Tables.transformValues(Table, Function)
Collection goodies

    // oldway
    Map<String, Map<Long, List<String>>> mapOld =
    new HashMap<String, Map<Long, List<String>>>();
    // the guava way
    Map<String, Map<Long, List<String>>> map =
Maps.newHashMap();
    // list
    ImmutableList<String> of = ImmutableList.of("a", "b", "c");
    // Same one for map
    ImmutableMap<String, String> map =
    ImmutableMap.of("key1", "value1", "key2", "value2");
    //list of ints
    List<Integer> theList = Ints.asList(1, 2, 3, 4, 522, 5, 6);
Load resources
When to use Guava?

• Temporary collections
• Mutable collections
• String Utils
• Check if (x==null)
• Always ?
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.
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>
Google Guava for cleaner code

More Related Content

What's hot

Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB
 
6η Επανάληψη, ΜΑΘΗΜΑΤΙΚΑ Δ΄ ΔΗΜΟΤΙΚΟΥ
6η Επανάληψη, ΜΑΘΗΜΑΤΙΚΑ Δ΄ ΔΗΜΟΤΙΚΟΥ6η Επανάληψη, ΜΑΘΗΜΑΤΙΚΑ Δ΄ ΔΗΜΟΤΙΚΟΥ
6η Επανάληψη, ΜΑΘΗΜΑΤΙΚΑ Δ΄ ΔΗΜΟΤΙΚΟΥteaghet
 
Γλώσσα Στ δημοτικού Ενότητες 7 και 9 (β')
Γλώσσα Στ δημοτικού Ενότητες 7 και 9 (β')Γλώσσα Στ δημοτικού Ενότητες 7 και 9 (β')
Γλώσσα Στ δημοτικού Ενότητες 7 και 9 (β')Christina Politaki
 
[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQLEDB
 
Unit testing with Qt test
Unit testing with Qt testUnit testing with Qt test
Unit testing with Qt testDavide Coppola
 
ECDL Windows Σημειώσεις 2/7
ECDL Windows Σημειώσεις 2/7ECDL Windows Σημειώσεις 2/7
ECDL Windows Σημειώσεις 2/7Michael Ntallas
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking frameworkPhat VU
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesLuis Goldster
 
Επαναληπτικές Ασκήσεις Γλώσσας 13ης Ενότητας: "Όλοι διαφορετικοί, όλοι ίδιοι"
Επαναληπτικές Ασκήσεις Γλώσσας 13ης Ενότητας: "Όλοι διαφορετικοί, όλοι ίδιοι"Επαναληπτικές Ασκήσεις Γλώσσας 13ης Ενότητας: "Όλοι διαφορετικοί, όλοι ίδιοι"
Επαναληπτικές Ασκήσεις Γλώσσας 13ης Ενότητας: "Όλοι διαφορετικοί, όλοι ίδιοι"Ηλιάδης Ηλίας
 
MongoDB .local Toronto 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pi...
MongoDB .local Toronto 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pi...MongoDB .local Toronto 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pi...
MongoDB .local Toronto 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pi...MongoDB
 
End to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaEnd to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaBabacar NIANG
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldYura Nosenko
 
Μαθηματικά Δ΄ ΄΄Επανάληψη 7ης Ενότητας, κεφ. 41 - 46΄΄
Μαθηματικά Δ΄ ΄΄Επανάληψη 7ης Ενότητας, κεφ. 41 - 46΄΄Μαθηματικά Δ΄ ΄΄Επανάληψη 7ης Ενότητας, κεφ. 41 - 46΄΄
Μαθηματικά Δ΄ ΄΄Επανάληψη 7ης Ενότητας, κεφ. 41 - 46΄΄Χρήστος Χαρμπής
 
Γλώσσα Δ΄. Eπανάληψη 1ης ενότητας: ΄΄Ένα ακόμα σκαλί...΄΄
Γλώσσα Δ΄. Eπανάληψη 1ης ενότητας: ΄΄Ένα ακόμα σκαλί...΄΄Γλώσσα Δ΄. Eπανάληψη 1ης ενότητας: ΄΄Ένα ακόμα σκαλί...΄΄
Γλώσσα Δ΄. Eπανάληψη 1ης ενότητας: ΄΄Ένα ακόμα σκαλί...΄΄Χρήστος Χαρμπής
 
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшe
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшeQA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшe
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшeQAFest
 
ECDL Internet Σημειώσεις 7/7
ECDL Internet Σημειώσεις 7/7ECDL Internet Σημειώσεις 7/7
ECDL Internet Σημειώσεις 7/7Michael Ntallas
 

What's hot (20)

Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB World 2019: Tips and Tricks++ for Querying and Indexing MongoDB
 
6η Επανάληψη, ΜΑΘΗΜΑΤΙΚΑ Δ΄ ΔΗΜΟΤΙΚΟΥ
6η Επανάληψη, ΜΑΘΗΜΑΤΙΚΑ Δ΄ ΔΗΜΟΤΙΚΟΥ6η Επανάληψη, ΜΑΘΗΜΑΤΙΚΑ Δ΄ ΔΗΜΟΤΙΚΟΥ
6η Επανάληψη, ΜΑΘΗΜΑΤΙΚΑ Δ΄ ΔΗΜΟΤΙΚΟΥ
 
Γλώσσα Στ δημοτικού Ενότητες 7 και 9 (β')
Γλώσσα Στ δημοτικού Ενότητες 7 και 9 (β')Γλώσσα Στ δημοτικού Ενότητες 7 και 9 (β')
Γλώσσα Στ δημοτικού Ενότητες 7 και 9 (β')
 
[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL
 
Unit testing with Qt test
Unit testing with Qt testUnit testing with Qt test
Unit testing with Qt test
 
ECDL Windows Σημειώσεις 2/7
ECDL Windows Σημειώσεις 2/7ECDL Windows Σημειώσεις 2/7
ECDL Windows Σημειώσεις 2/7
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Επαναληπτικές Ασκήσεις Γλώσσας 13ης Ενότητας: "Όλοι διαφορετικοί, όλοι ίδιοι"
Επαναληπτικές Ασκήσεις Γλώσσας 13ης Ενότητας: "Όλοι διαφορετικοί, όλοι ίδιοι"Επαναληπτικές Ασκήσεις Γλώσσας 13ης Ενότητας: "Όλοι διαφορετικοί, όλοι ίδιοι"
Επαναληπτικές Ασκήσεις Γλώσσας 13ης Ενότητας: "Όλοι διαφορετικοί, όλοι ίδιοι"
 
MongoDB .local Toronto 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pi...
MongoDB .local Toronto 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pi...MongoDB .local Toronto 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pi...
MongoDB .local Toronto 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pi...
 
End to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaEnd to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux Saga
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 world
 
Μαθηματικά Δ΄ ΄΄Επανάληψη 7ης Ενότητας, κεφ. 41 - 46΄΄
Μαθηματικά Δ΄ ΄΄Επανάληψη 7ης Ενότητας, κεφ. 41 - 46΄΄Μαθηματικά Δ΄ ΄΄Επανάληψη 7ης Ενότητας, κεφ. 41 - 46΄΄
Μαθηματικά Δ΄ ΄΄Επανάληψη 7ης Ενότητας, κεφ. 41 - 46΄΄
 
Γλώσσα Δ΄. Eπανάληψη 1ης ενότητας: ΄΄Ένα ακόμα σκαλί...΄΄
Γλώσσα Δ΄. Eπανάληψη 1ης ενότητας: ΄΄Ένα ακόμα σκαλί...΄΄Γλώσσα Δ΄. Eπανάληψη 1ης ενότητας: ΄΄Ένα ακόμα σκαλί...΄΄
Γλώσσα Δ΄. Eπανάληψη 1ης ενότητας: ΄΄Ένα ακόμα σκαλί...΄΄
 
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшe
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшeQA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшe
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшe
 
ECDL Internet Σημειώσεις 7/7
ECDL Internet Σημειώσεις 7/7ECDL Internet Σημειώσεις 7/7
ECDL Internet Σημειώσεις 7/7
 
PDBC
PDBCPDBC
PDBC
 

Viewers also liked

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
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidJordi Gerona
 
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon Berlin
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for androidEsa Firman
 
자바8 람다식 소개
자바8 람다식 소개자바8 람다식 소개
자바8 람다식 소개beom kyun choi
 
AVG Android App Performance Report by AVG Technologies
AVG Android App Performance Report by AVG TechnologiesAVG Android App Performance Report by AVG Technologies
AVG Android App Performance Report by AVG TechnologiesAVG Technologies
 
DE000010063015B4_all_pages
DE000010063015B4_all_pagesDE000010063015B4_all_pages
DE000010063015B4_all_pagesDr. Ingo Dahm
 
Curso de idiomas globo inglês livro002
Curso de idiomas globo inglês livro002Curso de idiomas globo inglês livro002
Curso de idiomas globo inglês livro002rosemere12
 
El ROI no es negociable - Marketing Digital para Startups - Parte 3
 El ROI no es negociable - Marketing Digital para Startups - Parte 3 El ROI no es negociable - Marketing Digital para Startups - Parte 3
El ROI no es negociable - Marketing Digital para Startups - Parte 3Welovroi
 
Career Mobility Itp Conference2011 Final
Career Mobility Itp Conference2011 FinalCareer Mobility Itp Conference2011 Final
Career Mobility Itp Conference2011 FinalVictoria Pazukha
 
Reading and writing a massive online hypertext - Meetup session 3
Reading and writing a massive online hypertext - Meetup session 3Reading and writing a massive online hypertext - Meetup session 3
Reading and writing a massive online hypertext - Meetup session 3William Hall
 
Real world citizenship
Real world citizenshipReal world citizenship
Real world citizenshipmrshixson
 
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11rtemerson
 
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89Cagliostro Puntodue
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaMite Mitreski
 
LESS CSS Processor
LESS CSS ProcessorLESS CSS Processor
LESS CSS Processorsdhoman
 

Viewers also liked (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
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
 
자바8 람다식 소개
자바8 람다식 소개자바8 람다식 소개
자바8 람다식 소개
 
AVG Android App Performance Report by AVG Technologies
AVG Android App Performance Report by AVG TechnologiesAVG Android App Performance Report by AVG Technologies
AVG Android App Performance Report by AVG Technologies
 
DE000010063015B4_all_pages
DE000010063015B4_all_pagesDE000010063015B4_all_pages
DE000010063015B4_all_pages
 
World Tech E S
World Tech  E SWorld Tech  E S
World Tech E S
 
Curso de idiomas globo inglês livro002
Curso de idiomas globo inglês livro002Curso de idiomas globo inglês livro002
Curso de idiomas globo inglês livro002
 
El ROI no es negociable - Marketing Digital para Startups - Parte 3
 El ROI no es negociable - Marketing Digital para Startups - Parte 3 El ROI no es negociable - Marketing Digital para Startups - Parte 3
El ROI no es negociable - Marketing Digital para Startups - Parte 3
 
Career Mobility Itp Conference2011 Final
Career Mobility Itp Conference2011 FinalCareer Mobility Itp Conference2011 Final
Career Mobility Itp Conference2011 Final
 
Canjs
CanjsCanjs
Canjs
 
Interstellar Designs
Interstellar DesignsInterstellar Designs
Interstellar Designs
 
Reading and writing a massive online hypertext - Meetup session 3
Reading and writing a massive online hypertext - Meetup session 3Reading and writing a massive online hypertext - Meetup session 3
Reading and writing a massive online hypertext - Meetup session 3
 
Real world citizenship
Real world citizenshipReal world citizenship
Real world citizenship
 
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
 
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
 
LESS CSS Processor
LESS CSS ProcessorLESS CSS Processor
LESS CSS Processor
 

Similar to Google Guava for cleaner code

Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introductiongosain20
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.jstimourian
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Monads in javascript
Monads in javascriptMonads in javascript
Monads in javascriptJana Karceska
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersMatthew Farwell
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
An Exploration of the Formal Properties of PromQL
An Exploration of the Formal Properties of PromQLAn Exploration of the Formal Properties of PromQL
An Exploration of the Formal Properties of PromQLBrian Brazil
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetJose Perez
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevJavaDayUA
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 

Similar to Google Guava for cleaner code (20)

Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Monads in javascript
Monads in javascriptMonads in javascript
Monads in javascript
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Groovy
GroovyGroovy
Groovy
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Miracle of std lib
Miracle of std libMiracle of std lib
Miracle of std lib
 
An Exploration of the Formal Properties of PromQL
An Exploration of the Formal Properties of PromQLAn Exploration of the Formal Properties of PromQL
An Exploration of the Formal Properties of PromQL
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 

More from Mite Mitreski

Getting all the 99.99(9) you always wanted
Getting all the 99.99(9) you always wanted Getting all the 99.99(9) you always wanted
Getting all the 99.99(9) you always wanted Mite Mitreski
 
Micro service pitfalls voxxed days istanbul 2015
Micro service pitfalls voxxed days istanbul 2015Micro service pitfalls voxxed days istanbul 2015
Micro service pitfalls voxxed days istanbul 2015Mite Mitreski
 
Devoxx 2014 : Sparky guide to bug free JavaScirpt
Devoxx 2014 : Sparky guide to bug free JavaScirptDevoxx 2014 : Sparky guide to bug free JavaScirpt
Devoxx 2014 : Sparky guide to bug free JavaScirptMite Mitreski
 
Microservice pitfalls
Microservice pitfalls Microservice pitfalls
Microservice pitfalls Mite Mitreski
 
Java2day 2013 : Modern workflows for javascript integration
Java2day 2013 : Modern workflows for javascript integrationJava2day 2013 : Modern workflows for javascript integration
Java2day 2013 : Modern workflows for javascript integrationMite Mitreski
 
Eclipse 10 years Party
Eclipse 10 years PartyEclipse 10 years Party
Eclipse 10 years PartyMite Mitreski
 

More from Mite Mitreski (8)

Getting all the 99.99(9) you always wanted
Getting all the 99.99(9) you always wanted Getting all the 99.99(9) you always wanted
Getting all the 99.99(9) you always wanted
 
Micro service pitfalls voxxed days istanbul 2015
Micro service pitfalls voxxed days istanbul 2015Micro service pitfalls voxxed days istanbul 2015
Micro service pitfalls voxxed days istanbul 2015
 
Devoxx 2014 : Sparky guide to bug free JavaScirpt
Devoxx 2014 : Sparky guide to bug free JavaScirptDevoxx 2014 : Sparky guide to bug free JavaScirpt
Devoxx 2014 : Sparky guide to bug free JavaScirpt
 
Microservice pitfalls
Microservice pitfalls Microservice pitfalls
Microservice pitfalls
 
Unix for developers
Unix for developersUnix for developers
Unix for developers
 
State of the lambda
State of the lambdaState of the lambda
State of the lambda
 
Java2day 2013 : Modern workflows for javascript integration
Java2day 2013 : Modern workflows for javascript integrationJava2day 2013 : Modern workflows for javascript integration
Java2day 2013 : Modern workflows for javascript integration
 
Eclipse 10 years Party
Eclipse 10 years PartyEclipse 10 years Party
Eclipse 10 years Party
 

Recently uploaded

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 

Recently uploaded (20)

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 

Google Guava for cleaner code

  • 1. Cleaner code with Guava Code samples @ git://github.com/mitemitreski/guava-examples.git @mitemitreski 08-02-2012
  • 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
  • 20. import com.google.common.cache.*; Cache<Integer, Customer> cache = CacheBuilder.newBuilder() .weakKeys() .maximumSize(10000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(new CacheLoader<Integer, Customer>() { @Override public Customer load(Integer key) throws Exception { return retreveCustomerForKey(key); } });
  • 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! }
  • 24. Filter collections Iterables Signature Collection type Filter method boolean all(Iterable, Predicate) Iterable Iterables.filter(Iterable, Predicate) boolean any(Iterable, Predicate) Iterator Iterators.filter(Iterator, Predicate) Collection Collections2.filter(Collection, Predicate)T find(Iterable, Predicate) Set Sets.filter(Set, Predicate) removeIf(Iterable, Predicate) SortedSet Sets.filter(SortedSet, Predicate) Map Maps.filterKeys(Map, Predicate) Maps.filterValues(Map, Maps.filterEntrie Predicate) SortedMap Maps.filterKeys(SortedMap, Predicate)Maps.filterValues(SortedMap, Predicate) Maps.filterEntrie Multimap Multimaps.filterKeys(Multimap, Predicate) Multimaps.filterValues(Multimap, Predic Multimaps.filterE
  • 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;     }   });
  • 26. Transform collections Collection type Transform method Iterable Iterables.transform(Iterable, Function) Iterator Iterators.transform(Iterator, Function) Collection Collections2.transform(Collection, Function) List Lists.transform(List, Function) Map* Maps.transformValues(Map, Function) Maps.transformEntries(Map, EntryTransfor SortedMap* Maps.transformValues(SortedMap, Function) Maps.transformEntries(SortedMap, EntryTr Multimaps.transformEntries(Mul Multimap* Multimaps.transformValues(Multimap, Function) timap, EntryTransformer) Multimaps.transformValues(ListMultimap Multimaps.transformEntries(List ListMultimap* , Function) Multimap, EntryTransformer) Table Tables.transformValues(Table, Function)
  • 27. Collection goodies // oldway Map<String, Map<Long, List<String>>> mapOld = new HashMap<String, Map<Long, List<String>>>(); // the guava way Map<String, Map<Long, List<String>>> map = Maps.newHashMap(); // list ImmutableList<String> of = ImmutableList.of("a", "b", "c"); // Same one for map ImmutableMap<String, String> map = ImmutableMap.of("key1", "value1", "key2", "value2"); //list of ints List<Integer> theList = Ints.asList(1, 2, 3, 4, 522, 5, 6);
  • 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>