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

AWS의 다양한 Compute 서비스(EC2, Lambda, ECS, Batch, Elastic Beanstalk)의 특징 이해하기 - 김...
AWS의 다양한 Compute 서비스(EC2, Lambda, ECS, Batch, Elastic Beanstalk)의 특징 이해하기 - 김...AWS의 다양한 Compute 서비스(EC2, Lambda, ECS, Batch, Elastic Beanstalk)의 특징 이해하기 - 김...
AWS의 다양한 Compute 서비스(EC2, Lambda, ECS, Batch, Elastic Beanstalk)의 특징 이해하기 - 김...Amazon Web Services Korea
 
Cross-account encryption with AWS KMS and Slack Enterprise Key Management - S...
Cross-account encryption with AWS KMS and Slack Enterprise Key Management - S...Cross-account encryption with AWS KMS and Slack Enterprise Key Management - S...
Cross-account encryption with AWS KMS and Slack Enterprise Key Management - S...Amazon Web Services
 
Introduction à scala
Introduction à scalaIntroduction à scala
Introduction à scalaSOAT
 
20분안에 스타트업이 알아야하는 AWS의 모든것 - 윤석찬 :: 스타트업얼라이언스 런치클럽
20분안에 스타트업이 알아야하는 AWS의 모든것 - 윤석찬 :: 스타트업얼라이언스 런치클럽20분안에 스타트업이 알아야하는 AWS의 모든것 - 윤석찬 :: 스타트업얼라이언스 런치클럽
20분안에 스타트업이 알아야하는 AWS의 모든것 - 윤석찬 :: 스타트업얼라이언스 런치클럽Amazon Web Services Korea
 
An introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel AvivAn introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel AvivAmazon Web Services
 
CI/CD pipelines on AWS - Builders Day Israel
CI/CD pipelines on AWS - Builders Day IsraelCI/CD pipelines on AWS - Builders Day Israel
CI/CD pipelines on AWS - Builders Day IsraelAmazon Web Services
 
Introduction to Cassandra
Introduction to CassandraIntroduction to Cassandra
Introduction to CassandraGokhan Atil
 
AWS Systems manager 2019
AWS Systems manager 2019AWS Systems manager 2019
AWS Systems manager 2019John Varghese
 
Data weave more operations
Data weave more operationsData weave more operations
Data weave more operationsRamakrishna kapa
 
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020 AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020 AWSKRUG - AWS한국사용자모임
 
Introduction to Apache Cassandra
Introduction to Apache CassandraIntroduction to Apache Cassandra
Introduction to Apache CassandraRobert Stupp
 
AWS CloudFormation Best Practices
AWS CloudFormation Best PracticesAWS CloudFormation Best Practices
AWS CloudFormation Best PracticesAmazon Web Services
 
如何利用 Amazon EMR 及Athena 打造高成本效益的大數據環境
如何利用 Amazon EMR 及Athena 打造高成本效益的大數據環境如何利用 Amazon EMR 及Athena 打造高成本效益的大數據環境
如何利用 Amazon EMR 及Athena 打造高成本效益的大數據環境Amazon Web Services
 
AWS January 2016 Webinar Series - Managing your Infrastructure as Code
AWS January 2016 Webinar Series - Managing your Infrastructure as CodeAWS January 2016 Webinar Series - Managing your Infrastructure as Code
AWS January 2016 Webinar Series - Managing your Infrastructure as CodeAmazon Web Services
 

What's hot (18)

AWS의 다양한 Compute 서비스(EC2, Lambda, ECS, Batch, Elastic Beanstalk)의 특징 이해하기 - 김...
AWS의 다양한 Compute 서비스(EC2, Lambda, ECS, Batch, Elastic Beanstalk)의 특징 이해하기 - 김...AWS의 다양한 Compute 서비스(EC2, Lambda, ECS, Batch, Elastic Beanstalk)의 특징 이해하기 - 김...
AWS의 다양한 Compute 서비스(EC2, Lambda, ECS, Batch, Elastic Beanstalk)의 특징 이해하기 - 김...
 
Cross-account encryption with AWS KMS and Slack Enterprise Key Management - S...
Cross-account encryption with AWS KMS and Slack Enterprise Key Management - S...Cross-account encryption with AWS KMS and Slack Enterprise Key Management - S...
Cross-account encryption with AWS KMS and Slack Enterprise Key Management - S...
 
Introduction à scala
Introduction à scalaIntroduction à scala
Introduction à scala
 
20분안에 스타트업이 알아야하는 AWS의 모든것 - 윤석찬 :: 스타트업얼라이언스 런치클럽
20분안에 스타트업이 알아야하는 AWS의 모든것 - 윤석찬 :: 스타트업얼라이언스 런치클럽20분안에 스타트업이 알아야하는 AWS의 모든것 - 윤석찬 :: 스타트업얼라이언스 런치클럽
20분안에 스타트업이 알아야하는 AWS의 모든것 - 윤석찬 :: 스타트업얼라이언스 런치클럽
 
An introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel AvivAn introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
 
CI/CD pipelines on AWS - Builders Day Israel
CI/CD pipelines on AWS - Builders Day IsraelCI/CD pipelines on AWS - Builders Day Israel
CI/CD pipelines on AWS - Builders Day Israel
 
Introduction to Cassandra
Introduction to CassandraIntroduction to Cassandra
Introduction to Cassandra
 
AWS Systems manager 2019
AWS Systems manager 2019AWS Systems manager 2019
AWS Systems manager 2019
 
Data weave more operations
Data weave more operationsData weave more operations
Data weave more operations
 
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020 AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020
 
Introduction to Apache Cassandra
Introduction to Apache CassandraIntroduction to Apache Cassandra
Introduction to Apache Cassandra
 
(ARC307) Infrastructure as Code
(ARC307) Infrastructure as Code(ARC307) Infrastructure as Code
(ARC307) Infrastructure as Code
 
AWS CloudFormation Best Practices
AWS CloudFormation Best PracticesAWS CloudFormation Best Practices
AWS CloudFormation Best Practices
 
如何利用 Amazon EMR 及Athena 打造高成本效益的大數據環境
如何利用 Amazon EMR 及Athena 打造高成本效益的大數據環境如何利用 Amazon EMR 及Athena 打造高成本效益的大數據環境
如何利用 Amazon EMR 及Athena 打造高成本效益的大數據環境
 
AWS January 2016 Webinar Series - Managing your Infrastructure as Code
AWS January 2016 Webinar Series - Managing your Infrastructure as CodeAWS January 2016 Webinar Series - Managing your Infrastructure as Code
AWS January 2016 Webinar Series - Managing your Infrastructure as Code
 
Apache hive
Apache hiveApache hive
Apache hive
 
Clean Code
Clean CodeClean Code
Clean Code
 
AWS Lambda
AWS LambdaAWS Lambda
AWS Lambda
 

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

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 

Recently uploaded (20)

Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
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🔝
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 

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>