SlideShare a Scribd company logo
1 of 21
Download to read offline
Facilite a vida com Guava
@programadorfsa
+RomualdoCosta
www.programadorfeirense.com.br
Problema: validação
boolean estaPreenchida = minhaString != null && minhaString.isEmpty();
Problema: ler um arquivo
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}
Software baseado em componentes
● Don’t repeat youself!
● Faça você mesmo ou pegue pronto.
● Interface bem definida e sem estado.
● Pode ser substituído por outro
componentes
Guava
● https://github.com/google/guava
● Java 1.6 ou maior
● Usadas em projetos Java do Google
● collections, caching, primitives support, concurrency libraries, common
annotations, string processing, I/O ...
Maven
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
Gradle
dependencies {
compile 'com.google.guava:guava:19.0'
}
Lidando com valores nulos
Integer a=5;
Integer b=null;
//algumas operações
Optional<Integer> possible=Optional.fromNullable(a);
System.out.println(possible.isPresent());//tem algo não nulo?
System.out.println(possible.or(10));//se for nulo, retorna 10 por padrão
System.out.println(MoreObjects.firstNonNull(a, b));//seleciona entre dois
valores
String nome=new String();
System.out.println(Strings.isNullOrEmpty(nome));
Pré condições
import static com.google.common.base.Preconditions.checkElementIndex;
Integer[]arr=new Integer[5];
//algum código
int index=5;
checkElementIndex(index, arr.length, "index");
/*
Exception in thread "main" java.lang.IndexOutOfBoundsException: index (5) must be
less than size (5)
at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:
310)
at br.gdg.fsa.Main.main(Main.java:43)
*/
Pré condições
import static com.google.common.base.Preconditions.checkNotNull;
Integer a=null;
checkNull(a);
/*
Exception in thread "main" java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:212)
at br.gdg.fsa.Main.main(Main.java:45)
*/
Pré condições
import static com.google.common.base.Preconditions.checkArgument;
int i=-1;
checkArgument(index >= 0, "Argument was %s but expected nonnegative", index);
/*
Exception in thread "main" java.lang.IllegalArgumentException: Argument was -1 but
expected nonnegative
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:146)
at br.gdg.fsa.Main.main(Main.java:46)
*/
Comparação de objetos
class Person implements Comparable<Person> {
public String lastName;
public String firstName;
public int zipCode;
public int compareTo(Person other) {
int cmp = lastName.compareTo(other.lastName);
if (cmp != 0) {
return cmp;
}
cmp = firstName.compareTo(other.firstName);
if (cmp != 0) {
return cmp;
}
return Integer.compare(zipCode, other.zipCode);
}
}
Comparação de objetos com Guava
class Person implements Comparable<Person> {
public String lastName;
public String firstName;
public int zipCode;
public int compareTo(Person that) {
return ComparisonChain.start()
.compare(this.lastName, that.lastName)
.compare(this.firstName, that.firstName)
.compare(this.zipCode, that.zipCode)
.result();
}
}
Ordenação
Integer[]arr=new Integer[5]; arr[0]=1; arr[1]=10; arr[2]=100; arr[3]
=1000; arr[4]=10000;
List<Integer> list = Lists.newArrayList(arr);
Ordering<Integer> ordering=Ordering.natural().reverse();
System.out.println(ordering.min(list)); //10000
Collections
Set<Type> copySet = Sets.newHashSet(elements);
List<String> theseElements = Lists.newArrayList("alpha", "beta",
"gamma");
List<Type> exactly100 = Lists.newArrayListWithCapacity(100);
List<Type> approx100 = Lists.newArrayListWithExpectedSize
(100);
Set<Type> approx100Set = Sets.newHashSetWithExpectedSize
(100);
Hashing
HashFunction hf = Hashing.md5();// seleciona algoritmo
HashCode hc = hf.newHasher()
.putLong(id)
.putString(name, Charsets.UTF_8)
.putObject(person, personFunnel)
.hash();
Funnel<Person> personFunnel = new Funnel<Person>() {
@Override
public void funnel(Person person, PrimitiveSink into) {
into
.putString(person.firstName, Charsets.UTF_8)
.putString(person.lastName, Charsets.UTF_8)
.putInt(person.zipcode);
}
};
IO
List<String> linhas = Files.readLines(arquivo, Charsets.UTF_8);
Closer closer = Closer.create();
try {
InputStream in = closer.register(openInputStream());
OutputStream out = closer.register(openOutputStream());
// do stuff with in and out
} catch (Throwable e) { // must catch Throwable
throw closer.rethrow(e);
} finally {
closer.close();
}
Ranges
Ranges
Range<Integer> range=Range.closed(1, 10);
ContiguousSet<Integer> values=ContiguousSet.create(range, DiscreteDomain.
integers());
List<Integer> list = Lists.newArrayList(values);
E muito mais...
● Imuttable Collections
● Novos Collections: BiMap, MultiMap, Table, RangeSet...
● EventBus
● Math
● Strings (split, join, match, charset)
● Caches
● Reflection
● Functional Idioms (Functions, Predicates)
● Primitives
Perguntas?

More Related Content

What's hot

名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
Tsuyoshi Yamamoto
 

What's hot (20)

Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
多治見IT勉強会 Groovy Grails
多治見IT勉強会 Groovy Grails多治見IT勉強会 Groovy Grails
多治見IT勉強会 Groovy Grails
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
Javascript foundations: Function modules
Javascript foundations: Function modulesJavascript foundations: Function modules
Javascript foundations: Function modules
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Send email
Send emailSend email
Send email
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
 
Puerto serialarduino
Puerto serialarduinoPuerto serialarduino
Puerto serialarduino
 
Codable routing
Codable routingCodable routing
Codable routing
 
TKPJava - Teaching Kids Programming - Core Java Langauge Concepts
TKPJava - Teaching Kids Programming - Core Java Langauge ConceptsTKPJava - Teaching Kids Programming - Core Java Langauge Concepts
TKPJava - Teaching Kids Programming - Core Java Langauge Concepts
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Introduction kot iin
Introduction kot iinIntroduction kot iin
Introduction kot iin
 
Groovy
GroovyGroovy
Groovy
 
Postman On Steroids
Postman On SteroidsPostman On Steroids
Postman On Steroids
 
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
 
Minion pool - a worker pool for nodejs
Minion pool - a worker pool for nodejsMinion pool - a worker pool for nodejs
Minion pool - a worker pool for nodejs
 
PyCon KR 2019 sprint - RustPython by example
PyCon KR 2019 sprint  - RustPython by examplePyCon KR 2019 sprint  - RustPython by example
PyCon KR 2019 sprint - RustPython by example
 
Synchronisation de périphériques avec Javascript et PouchDB
Synchronisation de périphériques avec Javascript et PouchDBSynchronisation de périphériques avec Javascript et PouchDB
Synchronisation de périphériques avec Javascript et PouchDB
 
Web Services
Web ServicesWeb Services
Web Services
 

Similar to Facilite a vida com guava

Implement threads and a GUI interface using advanced Java Swing clas.pdf
Implement threads and a GUI interface using advanced Java Swing clas.pdfImplement threads and a GUI interface using advanced Java Swing clas.pdf
Implement threads and a GUI interface using advanced Java Swing clas.pdf
amrishinda
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 

Similar to Facilite a vida com guava (20)

2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Typescript - A developer friendly javascript
Typescript - A developer friendly javascriptTypescript - A developer friendly javascript
Typescript - A developer friendly javascript
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Productive Programming in Groovy
Productive Programming in GroovyProductive Programming in Groovy
Productive Programming in Groovy
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript
 
ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?
 
Implement threads and a GUI interface using advanced Java Swing clas.pdf
Implement threads and a GUI interface using advanced Java Swing clas.pdfImplement threads and a GUI interface using advanced Java Swing clas.pdf
Implement threads and a GUI interface using advanced Java Swing clas.pdf
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Groovy Basics
Groovy BasicsGroovy Basics
Groovy Basics
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Stored Procedures and MUMPS for DivConq
 Stored Procedures and  MUMPS for DivConq  Stored Procedures and  MUMPS for DivConq
Stored Procedures and MUMPS for DivConq
 
This is to test a balanced tree. I need help testing an unbalanced t.pdf
This is to test a balanced tree. I need help testing an unbalanced t.pdfThis is to test a balanced tree. I need help testing an unbalanced t.pdf
This is to test a balanced tree. I need help testing an unbalanced t.pdf
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 

More from Romualdo Andre

More from Romualdo Andre (20)

Web, híbrido, cross compiled ou nativo: qual escolher?
Web, híbrido, cross compiled ou nativo: qual escolher?Web, híbrido, cross compiled ou nativo: qual escolher?
Web, híbrido, cross compiled ou nativo: qual escolher?
 
Python Class
Python ClassPython Class
Python Class
 
Dúvidas e respostas sobre carreira de TI: serviço público
Dúvidas e respostas sobre carreira de TI: serviço públicoDúvidas e respostas sobre carreira de TI: serviço público
Dúvidas e respostas sobre carreira de TI: serviço público
 
Tendências 2018
Tendências 2018Tendências 2018
Tendências 2018
 
Iniciando com javaScript 2017
Iniciando com javaScript 2017Iniciando com javaScript 2017
Iniciando com javaScript 2017
 
Codelab HTML e CSS
Codelab HTML e CSSCodelab HTML e CSS
Codelab HTML e CSS
 
Império JavaScript
Império JavaScriptImpério JavaScript
Império JavaScript
 
Angular 2 Básico
Angular 2 BásicoAngular 2 Básico
Angular 2 Básico
 
Codelab: TypeScript
Codelab: TypeScriptCodelab: TypeScript
Codelab: TypeScript
 
Introdução JavaScript e DOM 2016
Introdução JavaScript e DOM 2016Introdução JavaScript e DOM 2016
Introdução JavaScript e DOM 2016
 
Web, híbrido, cross compiled ou nativo: qual escolher?
Web, híbrido, cross compiled ou nativo: qual escolher?Web, híbrido, cross compiled ou nativo: qual escolher?
Web, híbrido, cross compiled ou nativo: qual escolher?
 
Android Studio: Primeiros Passos
Android Studio: Primeiros PassosAndroid Studio: Primeiros Passos
Android Studio: Primeiros Passos
 
Introdução JavaScript e DOM
Introdução JavaScript e DOMIntrodução JavaScript e DOM
Introdução JavaScript e DOM
 
Corrigindo o vestibular com Python e OpenCV
Corrigindo o vestibular com Python e OpenCVCorrigindo o vestibular com Python e OpenCV
Corrigindo o vestibular com Python e OpenCV
 
O programador e o super carro
O programador e o super carroO programador e o super carro
O programador e o super carro
 
Identificação de grupos de estudantes no Prosel usando Mapas de Kohonen
Identificação de grupos de estudantes no Prosel usando Mapas de KohonenIdentificação de grupos de estudantes no Prosel usando Mapas de Kohonen
Identificação de grupos de estudantes no Prosel usando Mapas de Kohonen
 
Exercício 2: Aplicações de Algoritmos Evolutivos
Exercício 2: Aplicações de Algoritmos EvolutivosExercício 2: Aplicações de Algoritmos Evolutivos
Exercício 2: Aplicações de Algoritmos Evolutivos
 
Uso de redes neurais na classificação de frutas
Uso de redes neurais na classificação de frutasUso de redes neurais na classificação de frutas
Uso de redes neurais na classificação de frutas
 
Introdução ao JavaScript e DOM
Introdução ao JavaScript e DOMIntrodução ao JavaScript e DOM
Introdução ao JavaScript e DOM
 
Introdução ao XML
Introdução ao XMLIntrodução ao XML
Introdução ao XML
 

Recently uploaded

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Recently uploaded (20)

Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

Facilite a vida com guava

  • 1. Facilite a vida com Guava @programadorfsa +RomualdoCosta www.programadorfeirense.com.br
  • 2. Problema: validação boolean estaPreenchida = minhaString != null && minhaString.isEmpty();
  • 3. Problema: ler um arquivo try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String everything = sb.toString(); }
  • 4. Software baseado em componentes ● Don’t repeat youself! ● Faça você mesmo ou pegue pronto. ● Interface bem definida e sem estado. ● Pode ser substituído por outro componentes
  • 5. Guava ● https://github.com/google/guava ● Java 1.6 ou maior ● Usadas em projetos Java do Google ● collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O ...
  • 8. Lidando com valores nulos Integer a=5; Integer b=null; //algumas operações Optional<Integer> possible=Optional.fromNullable(a); System.out.println(possible.isPresent());//tem algo não nulo? System.out.println(possible.or(10));//se for nulo, retorna 10 por padrão System.out.println(MoreObjects.firstNonNull(a, b));//seleciona entre dois valores String nome=new String(); System.out.println(Strings.isNullOrEmpty(nome));
  • 9. Pré condições import static com.google.common.base.Preconditions.checkElementIndex; Integer[]arr=new Integer[5]; //algum código int index=5; checkElementIndex(index, arr.length, "index"); /* Exception in thread "main" java.lang.IndexOutOfBoundsException: index (5) must be less than size (5) at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java: 310) at br.gdg.fsa.Main.main(Main.java:43) */
  • 10. Pré condições import static com.google.common.base.Preconditions.checkNotNull; Integer a=null; checkNull(a); /* Exception in thread "main" java.lang.NullPointerException at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:212) at br.gdg.fsa.Main.main(Main.java:45) */
  • 11. Pré condições import static com.google.common.base.Preconditions.checkArgument; int i=-1; checkArgument(index >= 0, "Argument was %s but expected nonnegative", index); /* Exception in thread "main" java.lang.IllegalArgumentException: Argument was -1 but expected nonnegative at com.google.common.base.Preconditions.checkArgument(Preconditions.java:146) at br.gdg.fsa.Main.main(Main.java:46) */
  • 12. Comparação de objetos class Person implements Comparable<Person> { public String lastName; public String firstName; public int zipCode; public int compareTo(Person other) { int cmp = lastName.compareTo(other.lastName); if (cmp != 0) { return cmp; } cmp = firstName.compareTo(other.firstName); if (cmp != 0) { return cmp; } return Integer.compare(zipCode, other.zipCode); } }
  • 13. Comparação de objetos com Guava class Person implements Comparable<Person> { public String lastName; public String firstName; public int zipCode; public int compareTo(Person that) { return ComparisonChain.start() .compare(this.lastName, that.lastName) .compare(this.firstName, that.firstName) .compare(this.zipCode, that.zipCode) .result(); } }
  • 14. Ordenação Integer[]arr=new Integer[5]; arr[0]=1; arr[1]=10; arr[2]=100; arr[3] =1000; arr[4]=10000; List<Integer> list = Lists.newArrayList(arr); Ordering<Integer> ordering=Ordering.natural().reverse(); System.out.println(ordering.min(list)); //10000
  • 15. Collections Set<Type> copySet = Sets.newHashSet(elements); List<String> theseElements = Lists.newArrayList("alpha", "beta", "gamma"); List<Type> exactly100 = Lists.newArrayListWithCapacity(100); List<Type> approx100 = Lists.newArrayListWithExpectedSize (100); Set<Type> approx100Set = Sets.newHashSetWithExpectedSize (100);
  • 16. Hashing HashFunction hf = Hashing.md5();// seleciona algoritmo HashCode hc = hf.newHasher() .putLong(id) .putString(name, Charsets.UTF_8) .putObject(person, personFunnel) .hash(); Funnel<Person> personFunnel = new Funnel<Person>() { @Override public void funnel(Person person, PrimitiveSink into) { into .putString(person.firstName, Charsets.UTF_8) .putString(person.lastName, Charsets.UTF_8) .putInt(person.zipcode); } };
  • 17. IO List<String> linhas = Files.readLines(arquivo, Charsets.UTF_8); Closer closer = Closer.create(); try { InputStream in = closer.register(openInputStream()); OutputStream out = closer.register(openOutputStream()); // do stuff with in and out } catch (Throwable e) { // must catch Throwable throw closer.rethrow(e); } finally { closer.close(); }
  • 19. Ranges Range<Integer> range=Range.closed(1, 10); ContiguousSet<Integer> values=ContiguousSet.create(range, DiscreteDomain. integers()); List<Integer> list = Lists.newArrayList(values);
  • 20. E muito mais... ● Imuttable Collections ● Novos Collections: BiMap, MultiMap, Table, RangeSet... ● EventBus ● Math ● Strings (split, join, match, charset) ● Caches ● Reflection ● Functional Idioms (Functions, Predicates) ● Primitives