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

What's hot

Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
NexThoughts Technologies
 
多治見IT勉強会 Groovy Grails
多治見IT勉強会 Groovy Grails多治見IT勉強会 Groovy Grails
多治見IT勉強会 Groovy Grails
Tsuyoshi Yamamoto
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
Websecurify
 
Javascript foundations: Function modules
Javascript foundations: Function modulesJavascript foundations: Function modules
Javascript foundations: Function modules
John Hunter
 
Bootstrap
BootstrapBootstrap
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
desistartups
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
Puerto serialarduino
Puerto serialarduinoPuerto serialarduino
Puerto serialarduino
zadkiel_123
 
Codable routing
Codable routingCodable routing
Codable routing
Pushkar Kulkarni
 
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
Lynn Langit
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
Andres Almiray
 
Introduction kot iin
Introduction kot iinIntroduction kot iin
Introduction kot iin
Jedsada Tiwongvokul
 
Groovy
GroovyGroovy
Postman On Steroids
Postman On SteroidsPostman On Steroids
Postman On Steroids
Sara Tornincasa
 
第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 nodejs
Marcelo 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 example
YunWon 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 PouchDB
Frank Rousseau
 
Web Services
Web ServicesWeb Services
Web Services
Victor Montalvão
 

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

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
loffenauer
 
Typescript - A developer friendly javascript
Typescript - A developer friendly javascriptTypescript - A developer friendly javascript
Typescript - A developer friendly javascript
pradiphudekar
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
David Furber
 
Productive Programming in Groovy
Productive Programming in GroovyProductive Programming in Groovy
Productive Programming in Groovy
Ganesh Samarthyam
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
Java best practices
Java best practicesJava best practices
Java best practices
Ray Toal
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
niklal
 
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
Johannes 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 JavaScript
Johannes 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.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 beyondMario Fusco
 
Groovy Basics
Groovy BasicsGroovy Basics
Groovy Basics
Wes Williams
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
Demian Holderegger
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
Andres Almiray
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
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.pdf
akaluza07
 
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
Sharon Rozinsky
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 

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

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
 
Python Class
Python ClassPython Class
Python Class
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úblico
Romualdo Andre
 
Tendências 2018
Tendências 2018Tendências 2018
Tendências 2018
Romualdo Andre
 
Iniciando com javaScript 2017
Iniciando com javaScript 2017Iniciando com javaScript 2017
Iniciando com javaScript 2017
Romualdo Andre
 
Codelab HTML e CSS
Codelab HTML e CSSCodelab HTML e CSS
Codelab HTML e CSS
Romualdo Andre
 
Império JavaScript
Império JavaScriptImpério JavaScript
Império JavaScript
Romualdo Andre
 
Angular 2 Básico
Angular 2 BásicoAngular 2 Básico
Angular 2 Básico
Romualdo Andre
 
Codelab: TypeScript
Codelab: TypeScriptCodelab: TypeScript
Codelab: TypeScript
Romualdo Andre
 
Introdução JavaScript e DOM 2016
Introdução JavaScript e DOM 2016Introdução JavaScript e DOM 2016
Introdução JavaScript e DOM 2016
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
 
Android Studio: Primeiros Passos
Android Studio: Primeiros PassosAndroid Studio: Primeiros Passos
Android Studio: Primeiros Passos
Romualdo Andre
 
Introdução JavaScript e DOM
Introdução JavaScript e DOMIntrodução JavaScript e DOM
Introdução JavaScript e DOM
Romualdo 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 OpenCV
Romualdo Andre
 
O programador e o super carro
O programador e o super carroO programador e o super carro
O programador e o super carro
Romualdo 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 Kohonen
Romualdo 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 Evolutivos
Romualdo 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 frutas
Romualdo Andre
 
Introdução ao JavaScript e DOM
Introdução ao JavaScript e DOMIntrodução ao JavaScript e DOM
Introdução ao JavaScript e DOM
Romualdo Andre
 
Introdução ao XML
Introdução ao XMLIntrodução ao XML
Introdução ao XML
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

Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 

Recently uploaded (20)

Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 

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