the core libraries you always wanted - google guava

47
@mitemitreski The core libraries you always wanted Google Guava

Upload: mite-mitreski

Post on 06-Aug-2015

53 views

Category:

Presentations & Public Speaking


4 download

TRANSCRIPT

Page 1: The core libraries you always wanted - Google Guava

@mitemitreski

The core libraries you always wanted

Google Guava

Page 2: The core libraries you always wanted - Google Guava
Page 3: The core libraries you always wanted - Google Guava

What is Google Guava?

com.google.common.annotationcom.google.common.basecom.google.common.collectcom.google.common.iocom.google.common.netcom.google.common.primitivescom.google.common.util.concurrent...

Page 4: The core libraries you always wanted - Google Guava

Code in slides

Page 5: The core libraries you always wanted - Google Guava

Apache 2 license

latest release is 18.0, released August 25, 2014.

Guava facts

Page 6: The core libraries you always wanted - Google Guava

NULL it is

"Null sucks." - Doug Lea

"I call it my billion-dollar mistake." - C. A. R. Hoare

Page 7: The core libraries you always wanted - Google Guava

Null is ambiguous

if ( x != null && x.someM()!=null && ) { // work with x.someM() }

Boolean isAwesome ; // can be NULL, TRUE, FALSE

Assert.notNull(x);Assert.notNull(x.someM()); // work with x.someM()

Page 8: The core libraries you always wanted - Google Guava

import com.google.common.base.*

@Testpublic void optionalExample() { Optional<Integer> possible = Optional.of(3); // Make optional of given type possible.isPresent(); // evaluate to true if nonNull possible.or(10); // evaluate to possible's value or default possible.get(); // evaluate to 3}

Page 9: The core libraries you always wanted - Google Guava

import com.google.common.base.*public void testNeverNullWithoutGuava() { Integer defaultId = null; Integer id = theUnknowMan.getId() != null ? theUnknowMan.getId() : defaultId; assertNotNull(id);}public void firstNotNull() { Integer a = Objects.firstNonNull(null, 3); // will evaluate to 3 Integer b = Objects.firstNonNull(9, 3); // //will evaluate to 9 assertEquals(Integer.valueOf(3), a); assertEquals(Integer.valueOf(9), b);}

Page 10: The core libraries you always wanted - Google Guava

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

private Customer theUnknowMan = new Customer();

@Test(expected = IllegalArgumentException.class)public void somePreconditions() { checkNotNull(theUnknowMan.getId()); // Will throw NPE checkState(!theUnknowMan.isSick()); // Will throw IllegalStateException checkArgument(theUnknowMan.getAddress() != null,

"We couldn't find the description for customer with id %s", theUnknowMan.getId());

}

Page 11: The core libraries you always wanted - Google Guava

JSR-305 Annotations for software defect detection

@Nullable @NotNull

1. javax.validation.constraints.NotNull - EE62. edu.umd.cs.findbugs.annotations.NonNull – Findbugs, Sonar3. javax.annotation.Nonnull – JSR-3054. com.intellij.annotations.NotNull - IntelliJIDEA

The Executive Committee voted to list this JSR as dormant in May 2012.

Page 12: The core libraries you always wanted - Google Guava

But JDK 8 has java.util.Optional

… and java.util.Objects

… and guava has com.google.common.base.MoreObjects

Page 13: The core libraries you always wanted - Google Guava

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

private Customer theUnknowMan = new Customer();

@Test(expected = IllegalArgumentException.class)public void somePreconditions() { checkNotNull(theUnknowMan.getId()); // Will throw NPE checkState(!theUnknowMan.isSick()); // Will throw IllegalStateException checkArgument(theUnknowMan.getAddress() != null,

"We couldn't find the description for customer with id %s", theUnknowMan.getId());

}

JDK8+ just use java.util.

Objects + Optional

Page 14: The core libraries you always wanted - Google Guava

API Deprecation

Page 15: The core libraries you always wanted - Google Guava

@Beta annotated API is subject to change any time

@Deprecated annotated API is removed in 18+ months after depreciation

Serialization compatibility is NOT guaranteed

Page 16: The core libraries you always wanted - Google Guava

Guava's "fluent" Comparator class.Ordering<Customer> ordering = Ordering .natural() .nullsFirst().onResultOf( new Function<Customer, Comparable>() { @Override public Comparable apply(Customer customer) { return customer.getName(); } } );

Page 17: The core libraries you always wanted - Google Guava

Wrapper overload

Page 18: The core libraries you always wanted - Google Guava

Character MatchersUse a predefined constant (examples)

• CharMatcher.WHITESPACE (tracks Unicode defn.)

• CharMatcher.JAVA_DIGIT

• CharMatcher.ASCII

• CharMatcher.ANY

Use a factory method (examples)

• CharMatcher.is('x')

• CharMatcher.isNot('_')

• CharMatcher.oneOf("aeiou").negate()

• CharMatcher.inRange('a', 'z').or(inRange('A','Z'))

Page 19: The core libraries you always wanted - Google Guava

Character Matchers

String noControl = CharMatcher.JAVA_ISO_CONTROL.removeFrom(string); String theDigits = CharMatcher.DIGIT.retainFrom(string); String lowerAndDigit = CharMatcher.or(CharMatcher.JAVA_DIGIT,CharMatcher.JAVA_LOWER_CASE).retainFrom(string);

Page 20: The core libraries you always wanted - Google Guava

import com.google.common.cache.*;

Cache<Integer, Customer> cache = CacheBuilder.newBuilder() .maximumSize(10000) .build();

Page 21: The core libraries you always wanted - Google Guava

Eviction

Cache<Integer, Customer> cache = CacheBuilder.newBuilder() .expireAfterWrite(2, TimeUnit.MINUTES) .build();

Cache<Integer, Customer> cache = CacheBuilder.newBuilder() .expireAfterAccess(2,TimeUnit.MINUTES) .build();

Page 22: The core libraries you always wanted - Google Guava

Eviction Cache<Integer, Customer> cache = CacheBuilder.newBuilder() .weigher(new Weigher<Integer, Customer>() { @Override public int weigh(Integer key, Customer value) { return value.getName().length(); } }).maximumWeight(20) //0 all good 21 evict something .build();

Page 23: The core libraries you always wanted - Google Guava

import com.google.common.cache.*;

Cache<Integer, Customer> cache = CacheBuilder.newBuilder() .weakKeys() .maximumSize(10000) .expireAfterWrite(10, TimeUnit.MINUTES) .build();

Page 24: The core libraries you always wanted - Google Guava

It’s all about the numbersCache<Integer, Customer> cache = CacheBuilder.newBuilder() .recordStats() .build();CacheStats stats = cache.stats();stats.hitRate();stats.averageLoadPenalty();stats.missCount();stats.missRate();

Page 25: The core libraries you always wanted - Google Guava

Map != Cache

● Map.get causes a type-safety hole ● Map.get is a read operation and users don't

expect it to also write ● Map.equals is not symmetric on a self-populating

Map

Page 26: The core libraries you always wanted - Google Guava

com.google.common.collect.*;

• Immutable Collections• Multimaps, Multisets, BiMaps... aka Google-Collections• Comparator-related utilities• Stuff similar to Apache commons collections• Some functional programming support(filter/transform/etc.)

Page 27: The core libraries you always wanted - Google Guava

MultiMap

Page 28: The core libraries you always wanted - Google Guava

BiMap

● BiMap<K, V> is Map<K,V> with unique values● Operations: all Map, inverse(), values() as Set● Throws an IllegalArgumentException if you attempt to

map a key to an already-present value

Page 29: The core libraries you always wanted - Google Guava

Functions and PredicatesFunction<String, Integer> lengthFunction = new Function<String, Integer>() {

public Integer apply(String string) { return string.length(); }};

Predicate<String> allCaps = new Predicate<String>() { public boolean apply(String string) { return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string); }};

Page 30: The core libraries you always wanted - Google Guava

Functions and Predicates

Function<String, Integer> lengthFunction = String::length;Predicate<String> allCaps = CharMatcher.JAVA_UPPER_CASE::matchesAllOf;

Page 31: The core libraries you always wanted - Google Guava

Functional aka Single Abstract Method interfaces - SAM

Page 32: The core libraries you always wanted - Google Guava

Functionality Guava JDK 8

Predicate apply(T input) test(T input)

Combining predicates Predicates.and/or/not Predicate.and/or/negate

Supplier Suplier.get Supplier.get

Joiner/StringJoiner Joiner.join() StringJoiner.add()

SettableFuture/CompletableFutu

reSettableFuture.set(T input) CompletableFuture.complete(T input)

Optional Optional.of/ofNullable/empty Optional.of/fromNullable/absent

Page 33: The core libraries you always wanted - Google Guava

Filter collections

SortedMap<String, String> map = new TreeMap<>(); map.put("1", "one"); map.put("2", "two"); map.put("3", null); map.put("4", "four"); SortedMap<String, String> filtered = Maps.filterValues(map, Predicates.notNull()); assertThat(filtered.size(), is(3)); // null entry for "3" is gone!

Page 34: The core libraries you always wanted - Google Guava

Filter collections

Page 35: The core libraries you always wanted - Google Guava

Transform collections

Page 36: The core libraries you always wanted - Google Guava

Java 8 - aggregate operations

http://docs.oracle.com/javase/tutorial/collections/streams/index.html

roster .stream() .filter(e -> e.getGender() == Person.Sex.MALE) .forEach(e -> System.out.println(e.getName());

Page 37: The core libraries you always wanted - Google Guava

Java 8 - aggregate operations

http://docs.oracle.com/javase/tutorial/collections/streams/index.html

double average = roster .stream() .filter(p -> p.getGender() == Person.Sex.MALE) .mapToInt(Person::getAge) .average() .getAsDouble();

Page 38: The core libraries you always wanted - Google Guava

Collection goodies// oldwayMap<String, Map<Long, List<String>>> mapOld = new HashMap<String, Map<Long, List<String>>>();// the guava wayMap<String, Map<Long, List<String>>> map = Maps.newHashMap();// listImmutableList<String> of = ImmutableList.of("a", "b", "c");// Same one for mapImmutableMap<String, String> theMap = ImmutableMap.of("key1", "value1", "key2", "value2");//list of intsList<Integer> theList = Ints.asList(1, 2, 3, 4, 522, 5, 6);

Page 39: The core libraries you always wanted - Google Guava

Load resources

Resources.getResource("com/tfnico/examples/guava/BaseTest.class");// instead of this:String location = "com/tfnico/examples/guava/BaseTest.class";URL resource2 = this.getClass().getClassLoader().getResource(location);Preconditions.checkArgument(resource2 != null, "resource %s not found", location);

Page 40: The core libraries you always wanted - Google Guava

HashingHashFunction hf = Hashing.md5();

Customer c = new Customer();// into is a primitive sinkFunnel<? super Customer> customerFunnel = (from, into) -> { into.putString(from.getName(),Charsets.UTF_8); into.putInt(from.getId());};HashCode hc = hf.newHasher() .putLong(2) .putString("Mite", Charsets.UTF_8) .putObject(c, customerFunnel) .hash();

Page 41: The core libraries you always wanted - Google Guava

Bloom filterBloomFilter<Customer> awesomeCusumers = BloomFilter.create(customerFunnel, 500, 0.01); List<Customer> friendsList = Lists.newArrayList( new Customer(), new Customer());

for(Customer friend : friendsList) { awesomeCusumers.put(friend);}Customer thatStrangeGuy = new Customer();if (awesomeCusumers.mightContain(thatStrangeGuy)) { //that strange guy is not a cusumer and we have reachet this line //probablility 0.01}

Page 42: The core libraries you always wanted - Google Guava

Bloom filter

Page 43: The core libraries you always wanted - Google Guava

When to use Guava?

● Temporary collections● Mutable collections● String Utils● Check if (x==null)● Always ?

Page 44: The core libraries you always wanted - Google Guava

Why use a Guava?

"I could just write that myself."

But… These things are much easier to mess up than itseems

•With a library, other people will make your code faster and betterfor You

Page 45: The core libraries you always wanted - Google Guava

Major stuff I did not mentioned

EventBusIOReflectionMathRanges

Page 46: The core libraries you always wanted - Google Guava
Page 47: The core libraries you always wanted - Google Guava

BG-JUG and JugMK community