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?

Facilite a vida com guava

  • 1.
    Facilite a vidacom Guava @programadorfsa +RomualdoCosta www.programadorfeirense.com.br
  • 2.
    Problema: validação boolean estaPreenchida= minhaString != null && minhaString.isEmpty();
  • 3.
    Problema: ler umarquivo 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 emcomponentes ● 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 ● Java1.6 ou maior ● Usadas em projetos Java do Google ● collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O ...
  • 6.
  • 7.
  • 8.
    Lidando com valoresnulos 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 staticcom.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 staticcom.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 staticcom.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 classPerson 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 objetoscom 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(); }
  • 18.
  • 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
  • 21.