21
Facilite a vida com Guava @programadorfsa +RomualdoCosta www.programadorfeirense.com.br

Facilite a vida com guava

Embed Size (px)

Citation preview

Page 1: Facilite a vida com guava

Facilite a vida com Guava@programadorfsa+RomualdoCostawww.programadorfeirense.com.br

Page 2: Facilite a vida com guava

Problema: validação

boolean estaPreenchida = minhaString != null && minhaString.isEmpty();

Page 3: Facilite a vida com guava

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();}

Page 4: Facilite a vida com guava

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

Page 5: Facilite a vida com guava

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 ...

Page 6: Facilite a vida com guava

Maven

<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version></dependency>

Page 7: Facilite a vida com guava

Gradle

dependencies { compile 'com.google.guava:guava:19.0'}

Page 8: Facilite a vida com guava

Lidando com valores nulos

Integer a=5;Integer b=null;//algumas operaçõesOptional<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ãoSystem.out.println(MoreObjects.firstNonNull(a, b));//seleciona entre dois valoresString nome=new String();System.out.println(Strings.isNullOrEmpty(nome));

Page 9: Facilite a vida com guava

Pré condições

import static com.google.common.base.Preconditions.checkElementIndex;

Integer[]arr=new Integer[5];//algum códigoint 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)*/

Page 10: Facilite a vida com guava

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)*/

Page 11: Facilite a vida com guava

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)*/

Page 12: Facilite a vida com guava

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); }}

Page 13: Facilite a vida com guava

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();

}}

Page 14: Facilite a vida com guava

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

Page 15: Facilite a vida com guava

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);

Page 16: Facilite a vida com guava

Hashing

HashFunction hf = Hashing.md5();// seleciona algoritmoHashCode 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); }};

Page 17: Facilite a vida com guava

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();}

Page 18: Facilite a vida com guava

Ranges

Page 19: Facilite a vida com guava

Ranges

Range<Integer> range=Range.closed(1, 10);ContiguousSet<Integer> values=ContiguousSet.create(range, DiscreteDomain.integers());List<Integer> list = Lists.newArrayList(values);

Page 20: Facilite a vida com guava

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

Page 21: Facilite a vida com guava

Perguntas?