SlideShare a Scribd company logo
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

PDF
お題でGroovyプログラミング: Part A
PDF
Groovyノススメ
PDF
Jggug 2010 330 Grails 1.3 観察
PDF
Json perl example
PPTX
Cis 216 – shell scripting
PDF
NoSQL Injections in Node.js - The case of MongoDB
PPTX
Functional programming with Immutable .JS
PDF
GoCracow #5 Bartlomiej klimczak - GoBDD
お題でGroovyプログラミング: Part A
Groovyノススメ
Jggug 2010 330 Grails 1.3 観察
Json perl example
Cis 216 – shell scripting
NoSQL Injections in Node.js - The case of MongoDB
Functional programming with Immutable .JS
GoCracow #5 Bartlomiej klimczak - GoBDD

What's hot (20)

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

Similar to Facilite a vida com guava (15)

PDF
The core libraries you always wanted - Google Guava
PDF
Google Guava - Core libraries for Java & Android
PDF
Google Guava for cleaner code
PDF
Guava tutorial
ODP
PDF
Google guava overview
PDF
Kotlin Overview (PT-BR)
PDF
Guava Overview. Part 1 @ Bucharest JUG #1
PDF
Java(8) The Good, The Bad and the Ugly
PDF
Java8 tgtbatu javaone
PPTX
Google guava(최종)
ODP
Guava
PDF
Java 8: the good, the bad and the ugly (JBCNConf 2017)
PDF
Java8 tgtbatu devoxxuk18
PDF
Google Guava
The core libraries you always wanted - Google Guava
Google Guava - Core libraries for Java & Android
Google Guava for cleaner code
Guava tutorial
Google guava overview
Kotlin Overview (PT-BR)
Guava Overview. Part 1 @ Bucharest JUG #1
Java(8) The Good, The Bad and the Ugly
Java8 tgtbatu javaone
Google guava(최종)
Guava
Java 8: the good, the bad and the ugly (JBCNConf 2017)
Java8 tgtbatu devoxxuk18
Google Guava
Ad

More from Romualdo Andre (20)

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

Recently uploaded (20)

PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Digital Strategies for Manufacturing Companies
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Transform Your Business with a Software ERP System
PPTX
assetexplorer- product-overview - presentation
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
medical staffing services at VALiNTRY
PDF
Nekopoi APK 2025 free lastest update
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
System and Network Administration Chapter 2
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Understanding Forklifts - TECH EHS Solution
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Upgrade and Innovation Strategies for SAP ERP Customers
Digital Strategies for Manufacturing Companies
Internet Downloader Manager (IDM) Crack 6.42 Build 41
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Wondershare Filmora 15 Crack With Activation Key [2025
Design an Analysis of Algorithms II-SECS-1021-03
Transform Your Business with a Software ERP System
assetexplorer- product-overview - presentation
2025 Textile ERP Trends: SAP, Odoo & Oracle
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
medical staffing services at VALiNTRY
Nekopoi APK 2025 free lastest update
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
System and Network Administration Chapter 2
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...

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