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

Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceDatabricks
 
Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupVictor Rentea
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Cost-based Query Optimization in Apache Phoenix using Apache Calcite
Cost-based Query Optimization in Apache Phoenix using Apache CalciteCost-based Query Optimization in Apache Phoenix using Apache Calcite
Cost-based Query Optimization in Apache Phoenix using Apache CalciteJulian Hyde
 
Hive 3 - a new horizon
Hive 3 - a new horizonHive 3 - a new horizon
Hive 3 - a new horizonThejas Nair
 
Introduction to regular expressions
Introduction to regular expressionsIntroduction to regular expressions
Introduction to regular expressionsBen Brumfield
 
Bulk Loading Data into Cassandra
Bulk Loading Data into CassandraBulk Loading Data into Cassandra
Bulk Loading Data into CassandraDataStax
 
Bulk Loading into Cassandra
Bulk Loading into CassandraBulk Loading into Cassandra
Bulk Loading into CassandraBrian Hess
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Data Warehouse (ETL) testing process
Data Warehouse (ETL) testing processData Warehouse (ETL) testing process
Data Warehouse (ETL) testing processRakesh Hansalia
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Hibernate start (하이버네이트 시작하기)
Hibernate start (하이버네이트 시작하기)Hibernate start (하이버네이트 시작하기)
Hibernate start (하이버네이트 시작하기)visual khh
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringEyob Lube
 

What's hot (20)

Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data Science
 
Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User Group
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Cost-based Query Optimization in Apache Phoenix using Apache Calcite
Cost-based Query Optimization in Apache Phoenix using Apache CalciteCost-based Query Optimization in Apache Phoenix using Apache Calcite
Cost-based Query Optimization in Apache Phoenix using Apache Calcite
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Hive 3 - a new horizon
Hive 3 - a new horizonHive 3 - a new horizon
Hive 3 - a new horizon
 
Introduction to regular expressions
Introduction to regular expressionsIntroduction to regular expressions
Introduction to regular expressions
 
Sql
SqlSql
Sql
 
Bulk Loading Data into Cassandra
Bulk Loading Data into CassandraBulk Loading Data into Cassandra
Bulk Loading Data into Cassandra
 
Bulk Loading into Cassandra
Bulk Loading into CassandraBulk Loading into Cassandra
Bulk Loading into Cassandra
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Data Warehouse (ETL) testing process
Data Warehouse (ETL) testing processData Warehouse (ETL) testing process
Data Warehouse (ETL) testing process
 
JDBC
JDBCJDBC
JDBC
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
 
Hibernate start (하이버네이트 시작하기)
Hibernate start (하이버네이트 시작하기)Hibernate start (하이버네이트 시작하기)
Hibernate start (하이버네이트 시작하기)
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 

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

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 

Recently uploaded (20)

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 

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>