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

The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agentsRafael Winterhalter
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and AnnotationsRoshan Deniyage
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 
Peeking inside the engine of ZIO SQL.pdf
Peeking inside the engine of ZIO SQL.pdfPeeking inside the engine of ZIO SQL.pdf
Peeking inside the engine of ZIO SQL.pdfJaroslavRegec1
 
SQLAlchemy Core: An Introduction
SQLAlchemy Core: An IntroductionSQLAlchemy Core: An Introduction
SQLAlchemy Core: An IntroductionJason Myers
 
JAVA DUMP SET.pdf
JAVA DUMP SET.pdfJAVA DUMP SET.pdf
JAVA DUMP SET.pdfanandn24
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programmingScott Wlaschin
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Scott Wlaschin
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...Philip Schwarz
 
LinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedListLinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedListMarcus Biel
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesVMware Tanzu
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithVictor Rentea
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean codeVictor Rentea
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
JSON-LD: JSON for the Social Web
JSON-LD: JSON for the Social WebJSON-LD: JSON for the Social Web
JSON-LD: JSON for the Social WebGregg Kellogg
 

What's hot (20)

Sql Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and Annotations
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Peeking inside the engine of ZIO SQL.pdf
Peeking inside the engine of ZIO SQL.pdfPeeking inside the engine of ZIO SQL.pdf
Peeking inside the engine of ZIO SQL.pdf
 
Clean code
Clean codeClean code
Clean code
 
SQLAlchemy Core: An Introduction
SQLAlchemy Core: An IntroductionSQLAlchemy Core: An Introduction
SQLAlchemy Core: An Introduction
 
Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
 
JAVA DUMP SET.pdf
JAVA DUMP SET.pdfJAVA DUMP SET.pdf
JAVA DUMP SET.pdf
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
 
LinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedListLinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedList
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
JSON-LD: JSON for the Social Web
JSON-LD: JSON for the Social WebJSON-LD: JSON for the Social Web
JSON-LD: JSON for the Social Web
 

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

Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
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
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
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
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
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.
 
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
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
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
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
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
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 

Recently uploaded (20)

Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
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
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
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
 
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
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.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...
 
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
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/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...
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
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
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 

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>