SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
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?

Contenu connexe

Tendances

多治見IT勉強会 Groovy Grails
多治見IT勉強会 Groovy Grails多治見IT勉強会 Groovy Grails
多治見IT勉強会 Groovy GrailsTsuyoshi Yamamoto
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.jsWebsecurify
 
Javascript foundations: Function modules
Javascript foundations: Function modulesJavascript foundations: Function modules
Javascript foundations: Function modulesJohn Hunter
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talkdesistartups
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
Puerto serialarduino
Puerto serialarduinoPuerto serialarduino
Puerto serialarduinozadkiel_123
 
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 ConceptsLynn Langit
 
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! GrailsプラグインTsuyoshi Yamamoto
 
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 nodejsMarcelo Gornstein
 
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 exampleYunWon Jeong
 
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 PouchDBFrank Rousseau
 

Tendances (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
 

Similaire à Facilite a vida com guava

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 Wsloffenauer
 
Typescript - A developer friendly javascript
Typescript - A developer friendly javascriptTypescript - A developer friendly javascript
Typescript - A developer friendly javascriptpradiphudekar
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Productive Programming in Groovy
Productive Programming in GroovyProductive Programming in Groovy
Productive Programming in GroovyGanesh Samarthyam
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScriptniklal
 
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 JavaScriptJohannes Hoppe
 
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 JavaScriptJohannes Hoppe
 
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.pdfamrishinda
 
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 beyondMario Fusco
 
Stored Procedures and MUMPS for DivConq
 Stored Procedures and  MUMPS for DivConq  Stored Procedures and  MUMPS for DivConq
Stored Procedures and MUMPS for DivConq eTimeline, LLC
 
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.pdfakaluza07
 
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 useSharon Rozinsky
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 

Similaire à 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 探検隊 -新たな聖杯をもとめて・・・-
 

Plus de Romualdo Andre

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?Romualdo Andre
 
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úblicoRomualdo Andre
 
Iniciando com javaScript 2017
Iniciando com javaScript 2017Iniciando com javaScript 2017
Iniciando com javaScript 2017Romualdo Andre
 
Introdução JavaScript e DOM 2016
Introdução JavaScript e DOM 2016Introdução JavaScript e DOM 2016
Introdução JavaScript e DOM 2016Romualdo Andre
 
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?Romualdo Andre
 
Android Studio: Primeiros Passos
Android Studio: Primeiros PassosAndroid Studio: Primeiros Passos
Android Studio: Primeiros PassosRomualdo Andre
 
Introdução JavaScript e DOM
Introdução JavaScript e DOMIntrodução JavaScript e DOM
Introdução JavaScript e DOMRomualdo Andre
 
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 OpenCVRomualdo Andre
 
O programador e o super carro
O programador e o super carroO programador e o super carro
O programador e o super carroRomualdo Andre
 
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 KohonenRomualdo Andre
 
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 EvolutivosRomualdo Andre
 
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 frutasRomualdo Andre
 
Introdução ao JavaScript e DOM
Introdução ao JavaScript e DOMIntrodução ao JavaScript e DOM
Introdução ao JavaScript e DOMRomualdo Andre
 

Plus de 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
 

Dernier

Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 

Dernier (20)

Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 

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