SlideShare a Scribd company logo
1 of 24
Download to read offline
.
.

Google’s Guava
Robert Bachmann

May 2, 2011

1 / 24
Outline

Basic utilities
Collections
Functions and Predicates
MapMaker

2 / 24
Example class (1/2)
public class Person {
public final String name;
public final String email ;
public final Gender gender ;
public Person ( String name , String email ,
Gender gender ) {
this.name = name;
this. email = email ;
this. gender = gender ;
}
// hashCode , equals
}

3 / 24
Example class (2/2)

@Override
public int hashCode () {
return Objects . hashCode (name , gender , email );
}
@Override
public boolean equals ( Object obj) {
if (this == obj) return true;
if (obj == null || getClass () != obj. getClass ())
return false ;
Person other = ( Person ) obj;
return Objects .equal (name , other.name)
&& Objects . equal (gender , other. gender )
&& Objects . equal (email , other.email );
}
4 / 24
Basic utilities

@Test
public void charsets () {
assertSame (
Charset . forName ("UTF -8"), // JDK
Charsets . UTF_8 // Guava
);
// same for: UTF16 , ISO_8859_1 , US_ASCII
}

5 / 24
Basic utilities

@Test
public void defaults () {
assertEquals (new Integer (0) ,
Defaults . defaultValue (int. class ));
assertEquals (new Double (0) ,
Defaults . defaultValue ( double . class ));
assertEquals (null ,
Defaults . defaultValue ( Double . class ));
assertEquals (null ,
Defaults . defaultValue ( String . class ));
assertEquals (null ,
Defaults . defaultValue ( Person . class ));
}

6 / 24
Basic utilities

// our test data
final Person alice =
new Person (" Alice Doe", " alice@example .com", Gender .F);
final Person bob =
new Person ("Bob Doe", " bob@example .com", Gender .M);
final Person john =
new Person ("John Doe", " john@example .com", Gender .M);
final Person jane =
new Person ("Jane Doe", " jane@example .com", Gender .F);

7 / 24
Basic utilities

@Test
public void equal () {
Person bob2 =
new Person ("Bob Doe", " bob@example .com", Gender .M);
boolean eq =
Objects . equal ("a", "a") &&
Objects . equal(bob , bob2) &&
Objects . equal(null , null );
assertTrue (eq );
assertFalse ( Objects . equal (null , "a"));
assertFalse ( Objects . equal ("a", null ));
}

8 / 24
Basic utilities
@Test
public void firstNonNull () {
Person p;
p = Objects . firstNonNull (null , bob );
assertSame (bob , p);
p = Objects . firstNonNull (alice , bob );
assertSame (alice , p);
p = Objects . firstNonNull (alice , null );
assertSame (alice , p);
try {
Objects . firstNonNull (null , null );
}
catch ( NullPointerException npe) { return ;}
fail("No exception ");
}

9 / 24
Basic utilities
public String titleForPerson ( Person person ) {
Preconditions . checkNotNull (person , " Person is null");
return Gender .M. equals ( person . gender ) ?
"Mr." : "Ms.";
}
@Test
public void preconditons () {
assertEquals ("Ms.", titleForPerson (jane ));
try {
titleForPerson (null );
}
catch ( NullPointerException npe) {
assertEquals (" Person is null", npe. getMessage ());
}
}

10 / 24
Basic utilities

@Test
public void morePreconditons () {
boolean expression = true;
Preconditions . checkArgument ( expression ); // throws IAE
Preconditions . checkState ( expression ); // throws ISE
// also:
// Preconditions . checkPositionIndex (index , size );
}

11 / 24
Basic utilities

// com. google . common .base. Equivalence <T>
public abstract interface Equivalence <T> {
public abstract boolean equivalent (
@Nullable T paramT1 ,
@Nullable T paramT2 );
public abstract int hash( @Nullable T paramT );
}

12 / 24
Basic utilities

@Test
public void joiner () {
Joiner joiner = Joiner .on("; "). skipNulls ();
String result = joiner .join('X' ,1,null ,23);
assertEquals ("X; 1; 23", result );
joiner = Joiner .on(':'). useForNull ("<missing >");
result = joiner .join('X' ,1,null ,23);
assertEquals ("X:1:< missing >:23", result );
}

13 / 24
Basic utilities

@Test
public void splitter () {
Iterable <String > parts =
Splitter .on(','). split ("foo ,,bar , quux");
String [] array = Iterables . toArray (parts , String .class );
assertEquals (new String []{"foo","","bar"," quux"},
array );
parts = Splitter .on(','). omitEmptyStrings ()
. split ("foo ,,bar , quux");
array = Iterables . toArray (parts , String .class );
assertEquals (new String []{"foo","bar"," quux"}, array );
}

14 / 24
Basic utilities

@Test
public void equivalence () {
Equivalence <Object > eq = Equivalences . equals ();
Equivalence <Object > same = Equivalences . identity ();
String s1 = "abc";
String s2 = String . format ("ab%s", "c");
assertTrue (eq. equivalent (s1 , s2 ));
assertFalse (same. equivalent (s1 , s2 ));
}

15 / 24
Basic utilities
Equivalence <String > eqIC = new Equivalence <String >() {
@Override
public boolean equivalent ( String a, String b) {
return (a == null) ? (b == null)
: a. equalsIgnoreCase (b);
}
@Override
public int hash( String s) {
return (s == null) ? 0 : s. toLowerCase (). hashCode ();
}
};
@Test
public void customEquivalence () {
assertTrue (eqIC. equivalent ("abc", "ABC"));
}
16 / 24
Basic utilities

@Test
public void pairwiseEquivalence () {
List <String > list = new ArrayList <String >();
list.add("a");
list.add("b");
List <String > list2 = new LinkedList <String >();
list2.add("a");
list2 .add("B");
boolean eq =
Equivalences . pairwise (eqIC ). equivalent (list , list2 );
assertTrue (eq );
}

17 / 24
Collections

BiMap
ClassToInstanceMap
Constraint
Forwarding Collections
Multiset
Multimap
Interner
Table

18 / 24
Collections

@Test
public void utils () {
List <Person > persons =
Lists. newArrayList (alice , bob );
assertEquals (2, persons .size ());
}

19 / 24
Collections

@Test
public void immutable () {
ImmutableList <Person > persons =
ImmutableList .of(alice ,bob );
assertEquals (2, persons .size ());
try {
persons .add(john );
}
catch ( UnsupportedOperationException uoe) {
return ;
}
fail("No exception ");
}

20 / 24
Functions and Predicates

Function <Person , String > titleFunc =
new Function <Person , String >() {
@Override
public String apply ( Person p) {
return titleForPerson (p) + " " + p.name;
}
};

21 / 24
Functions and Predicates

@Test
public void apply () {
ImmutableList <Person > persons =
ImmutableList .of(alice ,bob );
List <String > names =
Lists. transform (persons , titleFunc );
assertEquals ("Ms. Alice Doe", names.get (0));
assertEquals ("Mr. Bob Doe", names.get (1));
assertEquals (2, names .size ());
}

22 / 24
Functions and Predicates
@Test
public void filter () {
ImmutableList <Person > persons =
ImmutableList .of(alice ,bob );
Iterable <Person > females =
Iterables . filter (persons , new Predicate <Person >() {
@Override
public boolean apply ( Person input) {
return Gender .F. equals ( input. gender );
}
});
for ( Person p : females ) {
assertSame (p, alice );
}
}

23 / 24
MapMaker

ConcurrentMap <Key , Graph > graphs = new MapMaker ()
. expireAfterWrite (10 , TimeUnit . MINUTES )
. makeComputingMap (
new Function <Key , Graph >() {
public Graph apply (Key key) {
return createExpensiveGraph (key );
}
});

24 / 24

More Related Content

What's hot

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
 
Java весна 2013 лекция 5
Java весна 2013 лекция 5Java весна 2013 лекция 5
Java весна 2013 лекция 5Technopark
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitVaclav Pech
 
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
 
From java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFrom java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFabio Collini
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
Ciklum net sat12112011-alexander fomin-expressions and all, all, all
Ciklum net sat12112011-alexander fomin-expressions and all, all, allCiklum net sat12112011-alexander fomin-expressions and all, all, all
Ciklum net sat12112011-alexander fomin-expressions and all, all, allCiklum Ukraine
 
GPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstractionGPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstractionVaclav Pech
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)Makoto Yamazaki
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Ontico
 

What's hot (20)

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
 
Java весна 2013 лекция 5
Java весна 2013 лекция 5Java весна 2013 лекция 5
Java весна 2013 лекция 5
 
Week 9 IUB c#
Week 9 IUB c#Week 9 IUB c#
Week 9 IUB c#
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
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
 
Google guava
Google guavaGoogle guava
Google guava
 
Suit case class
Suit case classSuit case class
Suit case class
 
From java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFrom java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+k
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Ciklum net sat12112011-alexander fomin-expressions and all, all, all
Ciklum net sat12112011-alexander fomin-expressions and all, all, allCiklum net sat12112011-alexander fomin-expressions and all, all, all
Ciklum net sat12112011-alexander fomin-expressions and all, all, all
 
Lodash js
Lodash jsLodash js
Lodash js
 
GPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstractionGPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstraction
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 

Viewers also liked

C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language ComparisonRobert Bachmann
 
Características clínicas de una serie de pacientes con amnesia global trans...
Características clínicas de una serie de pacientes con amnesia global trans...Características clínicas de una serie de pacientes con amnesia global trans...
Características clínicas de una serie de pacientes con amnesia global trans...Javier Camiña Muñiz
 
FMP Storyboard
FMP StoryboardFMP Storyboard
FMP Storyboard7jebarrett
 
Sesión anatomopatológica. Discusión. [caso cerrado]
Sesión anatomopatológica. Discusión. [caso cerrado]Sesión anatomopatológica. Discusión. [caso cerrado]
Sesión anatomopatológica. Discusión. [caso cerrado]Javier Camiña Muñiz
 
Unidad I Análisis Vectorial
Unidad I Análisis VectorialUnidad I Análisis Vectorial
Unidad I Análisis VectorialMaria Naar
 
Trastornos motores asociados a demencia frontotemporal.
Trastornos motores asociados a demencia frontotemporal. Trastornos motores asociados a demencia frontotemporal.
Trastornos motores asociados a demencia frontotemporal. Javier Camiña Muñiz
 
Retirada de medicación antiepiléptica.
Retirada de medicación antiepiléptica. Retirada de medicación antiepiléptica.
Retirada de medicación antiepiléptica. Javier Camiña Muñiz
 
Danielle davis learning theory
Danielle davis   learning theoryDanielle davis   learning theory
Danielle davis learning theorydaneedavis
 
Slide ken18 nov2013
Slide ken18 nov2013Slide ken18 nov2013
Slide ken18 nov2013learnerchamp
 
Organizing edmngt
Organizing edmngtOrganizing edmngt
Organizing edmngtDatu jhed
 
Utilidad del EEG en el área de urgencias de un hospital de tercer nivel
Utilidad del EEG en el área de urgencias de un hospital de tercer nivelUtilidad del EEG en el área de urgencias de un hospital de tercer nivel
Utilidad del EEG en el área de urgencias de un hospital de tercer nivelJavier Camiña Muñiz
 
Biomarcadores de enfermedad de Alzheimer en LCR según PET-FDG cerebral.
Biomarcadores de enfermedad de Alzheimer en LCR según PET-FDG cerebral.Biomarcadores de enfermedad de Alzheimer en LCR según PET-FDG cerebral.
Biomarcadores de enfermedad de Alzheimer en LCR según PET-FDG cerebral.Javier Camiña Muñiz
 
Old techniques of SEO
Old techniques of SEOOld techniques of SEO
Old techniques of SEOMoney Grind
 

Viewers also liked (20)

Java 8
Java 8Java 8
Java 8
 
JNA
JNAJNA
JNA
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
 
Jython
JythonJython
Jython
 
Sv eng ordbok-2012
Sv eng ordbok-2012Sv eng ordbok-2012
Sv eng ordbok-2012
 
Características clínicas de una serie de pacientes con amnesia global trans...
Características clínicas de una serie de pacientes con amnesia global trans...Características clínicas de una serie de pacientes con amnesia global trans...
Características clínicas de una serie de pacientes con amnesia global trans...
 
FMP Storyboard
FMP StoryboardFMP Storyboard
FMP Storyboard
 
Sesión anatomopatológica. Discusión. [caso cerrado]
Sesión anatomopatológica. Discusión. [caso cerrado]Sesión anatomopatológica. Discusión. [caso cerrado]
Sesión anatomopatológica. Discusión. [caso cerrado]
 
Behaviorism Powerpoint
Behaviorism PowerpointBehaviorism Powerpoint
Behaviorism Powerpoint
 
Unidad I Análisis Vectorial
Unidad I Análisis VectorialUnidad I Análisis Vectorial
Unidad I Análisis Vectorial
 
Trastornos motores asociados a demencia frontotemporal.
Trastornos motores asociados a demencia frontotemporal. Trastornos motores asociados a demencia frontotemporal.
Trastornos motores asociados a demencia frontotemporal.
 
Retirada de medicación antiepiléptica.
Retirada de medicación antiepiléptica. Retirada de medicación antiepiléptica.
Retirada de medicación antiepiléptica.
 
Danielle davis learning theory
Danielle davis   learning theoryDanielle davis   learning theory
Danielle davis learning theory
 
Slide ken18 nov2013
Slide ken18 nov2013Slide ken18 nov2013
Slide ken18 nov2013
 
Organizing edmngt
Organizing edmngtOrganizing edmngt
Organizing edmngt
 
Cefalea en la mujer.
Cefalea en la mujer. Cefalea en la mujer.
Cefalea en la mujer.
 
Utilidad del EEG en el área de urgencias de un hospital de tercer nivel
Utilidad del EEG en el área de urgencias de un hospital de tercer nivelUtilidad del EEG en el área de urgencias de un hospital de tercer nivel
Utilidad del EEG en el área de urgencias de un hospital de tercer nivel
 
Behaviorism Powerpoint
Behaviorism PowerpointBehaviorism Powerpoint
Behaviorism Powerpoint
 
Biomarcadores de enfermedad de Alzheimer en LCR según PET-FDG cerebral.
Biomarcadores de enfermedad de Alzheimer en LCR según PET-FDG cerebral.Biomarcadores de enfermedad de Alzheimer en LCR según PET-FDG cerebral.
Biomarcadores de enfermedad de Alzheimer en LCR según PET-FDG cerebral.
 
Old techniques of SEO
Old techniques of SEOOld techniques of SEO
Old techniques of SEO
 

Similar to Google's Guava

Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Andrey Akinshin
 
Java 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR BeneluxJava 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR Beneluxyohanbeschi
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfShashikantSathe3
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
Data Types and Processing in ES6
Data Types and Processing in ES6Data Types and Processing in ES6
Data Types and Processing in ES6m0bz
 
JDD2015: Where Test Doubles can lead you... - Sebastian Malaca
JDD2015: Where Test Doubles can lead you...  - Sebastian Malaca JDD2015: Where Test Doubles can lead you...  - Sebastian Malaca
JDD2015: Where Test Doubles can lead you... - Sebastian Malaca PROIDEA
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesNebojša Vukšić
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfNicholasflqStewartl
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Codemotion
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
 
public class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfpublic class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfarjuncp10
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 

Similar to Google's Guava (20)

Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?
 
Java 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR BeneluxJava 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR Benelux
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Data Types and Processing in ES6
Data Types and Processing in ES6Data Types and Processing in ES6
Data Types and Processing in ES6
 
JDD2015: Where Test Doubles can lead you... - Sebastian Malaca
JDD2015: Where Test Doubles can lead you...  - Sebastian Malaca JDD2015: Where Test Doubles can lead you...  - Sebastian Malaca
JDD2015: Where Test Doubles can lead you... - Sebastian Malaca
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdf
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Java generics
Java genericsJava generics
Java generics
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
public class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfpublic class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdf
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Google's Guava

  • 3. Example class (1/2) public class Person { public final String name; public final String email ; public final Gender gender ; public Person ( String name , String email , Gender gender ) { this.name = name; this. email = email ; this. gender = gender ; } // hashCode , equals } 3 / 24
  • 4. Example class (2/2) @Override public int hashCode () { return Objects . hashCode (name , gender , email ); } @Override public boolean equals ( Object obj) { if (this == obj) return true; if (obj == null || getClass () != obj. getClass ()) return false ; Person other = ( Person ) obj; return Objects .equal (name , other.name) && Objects . equal (gender , other. gender ) && Objects . equal (email , other.email ); } 4 / 24
  • 5. Basic utilities @Test public void charsets () { assertSame ( Charset . forName ("UTF -8"), // JDK Charsets . UTF_8 // Guava ); // same for: UTF16 , ISO_8859_1 , US_ASCII } 5 / 24
  • 6. Basic utilities @Test public void defaults () { assertEquals (new Integer (0) , Defaults . defaultValue (int. class )); assertEquals (new Double (0) , Defaults . defaultValue ( double . class )); assertEquals (null , Defaults . defaultValue ( Double . class )); assertEquals (null , Defaults . defaultValue ( String . class )); assertEquals (null , Defaults . defaultValue ( Person . class )); } 6 / 24
  • 7. Basic utilities // our test data final Person alice = new Person (" Alice Doe", " alice@example .com", Gender .F); final Person bob = new Person ("Bob Doe", " bob@example .com", Gender .M); final Person john = new Person ("John Doe", " john@example .com", Gender .M); final Person jane = new Person ("Jane Doe", " jane@example .com", Gender .F); 7 / 24
  • 8. Basic utilities @Test public void equal () { Person bob2 = new Person ("Bob Doe", " bob@example .com", Gender .M); boolean eq = Objects . equal ("a", "a") && Objects . equal(bob , bob2) && Objects . equal(null , null ); assertTrue (eq ); assertFalse ( Objects . equal (null , "a")); assertFalse ( Objects . equal ("a", null )); } 8 / 24
  • 9. Basic utilities @Test public void firstNonNull () { Person p; p = Objects . firstNonNull (null , bob ); assertSame (bob , p); p = Objects . firstNonNull (alice , bob ); assertSame (alice , p); p = Objects . firstNonNull (alice , null ); assertSame (alice , p); try { Objects . firstNonNull (null , null ); } catch ( NullPointerException npe) { return ;} fail("No exception "); } 9 / 24
  • 10. Basic utilities public String titleForPerson ( Person person ) { Preconditions . checkNotNull (person , " Person is null"); return Gender .M. equals ( person . gender ) ? "Mr." : "Ms."; } @Test public void preconditons () { assertEquals ("Ms.", titleForPerson (jane )); try { titleForPerson (null ); } catch ( NullPointerException npe) { assertEquals (" Person is null", npe. getMessage ()); } } 10 / 24
  • 11. Basic utilities @Test public void morePreconditons () { boolean expression = true; Preconditions . checkArgument ( expression ); // throws IAE Preconditions . checkState ( expression ); // throws ISE // also: // Preconditions . checkPositionIndex (index , size ); } 11 / 24
  • 12. Basic utilities // com. google . common .base. Equivalence <T> public abstract interface Equivalence <T> { public abstract boolean equivalent ( @Nullable T paramT1 , @Nullable T paramT2 ); public abstract int hash( @Nullable T paramT ); } 12 / 24
  • 13. Basic utilities @Test public void joiner () { Joiner joiner = Joiner .on("; "). skipNulls (); String result = joiner .join('X' ,1,null ,23); assertEquals ("X; 1; 23", result ); joiner = Joiner .on(':'). useForNull ("<missing >"); result = joiner .join('X' ,1,null ,23); assertEquals ("X:1:< missing >:23", result ); } 13 / 24
  • 14. Basic utilities @Test public void splitter () { Iterable <String > parts = Splitter .on(','). split ("foo ,,bar , quux"); String [] array = Iterables . toArray (parts , String .class ); assertEquals (new String []{"foo","","bar"," quux"}, array ); parts = Splitter .on(','). omitEmptyStrings () . split ("foo ,,bar , quux"); array = Iterables . toArray (parts , String .class ); assertEquals (new String []{"foo","bar"," quux"}, array ); } 14 / 24
  • 15. Basic utilities @Test public void equivalence () { Equivalence <Object > eq = Equivalences . equals (); Equivalence <Object > same = Equivalences . identity (); String s1 = "abc"; String s2 = String . format ("ab%s", "c"); assertTrue (eq. equivalent (s1 , s2 )); assertFalse (same. equivalent (s1 , s2 )); } 15 / 24
  • 16. Basic utilities Equivalence <String > eqIC = new Equivalence <String >() { @Override public boolean equivalent ( String a, String b) { return (a == null) ? (b == null) : a. equalsIgnoreCase (b); } @Override public int hash( String s) { return (s == null) ? 0 : s. toLowerCase (). hashCode (); } }; @Test public void customEquivalence () { assertTrue (eqIC. equivalent ("abc", "ABC")); } 16 / 24
  • 17. Basic utilities @Test public void pairwiseEquivalence () { List <String > list = new ArrayList <String >(); list.add("a"); list.add("b"); List <String > list2 = new LinkedList <String >(); list2.add("a"); list2 .add("B"); boolean eq = Equivalences . pairwise (eqIC ). equivalent (list , list2 ); assertTrue (eq ); } 17 / 24
  • 19. Collections @Test public void utils () { List <Person > persons = Lists. newArrayList (alice , bob ); assertEquals (2, persons .size ()); } 19 / 24
  • 20. Collections @Test public void immutable () { ImmutableList <Person > persons = ImmutableList .of(alice ,bob ); assertEquals (2, persons .size ()); try { persons .add(john ); } catch ( UnsupportedOperationException uoe) { return ; } fail("No exception "); } 20 / 24
  • 21. Functions and Predicates Function <Person , String > titleFunc = new Function <Person , String >() { @Override public String apply ( Person p) { return titleForPerson (p) + " " + p.name; } }; 21 / 24
  • 22. Functions and Predicates @Test public void apply () { ImmutableList <Person > persons = ImmutableList .of(alice ,bob ); List <String > names = Lists. transform (persons , titleFunc ); assertEquals ("Ms. Alice Doe", names.get (0)); assertEquals ("Mr. Bob Doe", names.get (1)); assertEquals (2, names .size ()); } 22 / 24
  • 23. Functions and Predicates @Test public void filter () { ImmutableList <Person > persons = ImmutableList .of(alice ,bob ); Iterable <Person > females = Iterables . filter (persons , new Predicate <Person >() { @Override public boolean apply ( Person input) { return Gender .F. equals ( input. gender ); } }); for ( Person p : females ) { assertSame (p, alice ); } } 23 / 24
  • 24. MapMaker ConcurrentMap <Key , Graph > graphs = new MapMaker () . expireAfterWrite (10 , TimeUnit . MINUTES ) . makeComputingMap ( new Function <Key , Graph >() { public Graph apply (Key key) { return createExpensiveGraph (key ); } }); 24 / 24