Google Guava
Upcoming SlideShare
Loading in...5
×
 

Google Guava

on

  • 917 views

 

Statistics

Views

Total Views
917
Views on SlideShare
846
Embed Views
71

Actions

Likes
4
Downloads
34
Comments
0

2 Embeds 71

http://www.jug.lv 58
http://jug.lv 13

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Google Guava Google Guava Presentation Transcript

    • Google Guavaby Yuriy KrutkoJava Developer
    • Common MythsGuava is a fruitGuavas (singular Guava, English pronunciation: /ˈgwɑː.və/[2]) areplants in the Myrtle family (Myrtaceae) genus Psidium (meaning"pomegranate" in Latin)Guava is Google CollectionsGuava misuses functional idioms
    • Whats inside Strings Ordering ThrowablesConcurrency Preconditions Collections Reflection EventBus Objects Hashing Caches I/O Math Primitives Ranges
    • Why Guava?• Guava is a productivity multiplier• I Couldve Invented That• "Know and use the libraries”• Dont reinvent the wheel.• Could not be included into Java API
    • Guava Design Principles• API is the best solution for use case.• Obvious and intuitive outside. "Smart" inside.• Encourage good code habits.• Generic tools that can be composed.• Emphasize maintainability.
    • equals, hashCode, toStringCode it yourselfGenerate using tools (e.g. Eclipse)Use Guava Objects class
    • Generatedprivate String firstName;private String secondName;@Overridepublic String toString() { return "PersonGenerated [firstName=" + firstName + ", secondName=" + secondName + "]";}@Overridepublic int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((secondName == null) ? 0 : secondName.hashCode()); return result;}
    • Generate@Overridepublic boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PersonGenerated other = (PersonGenerated) obj; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (secondName == null) { if (other.secondName != null) return false; } else if (!secondName.equals(other.secondName)) return false; return true;}
    • Objectsprivate String firstName;private String secondName;@Overridepublic int hashCode() { return Objects.hashCode(firstName, secondName);}@Overridepublic boolean equals(Object obj) { if (obj instanceof PersonGuava) { PersonGuava other = (PersonGuava) obj; return Objects.equal(firstName, other.firstName) && Objects.equal(secondName, other.secondName); } return false;}@Overridepublic String toString() { return Objects.toStringHelper(this) .add("firstName", firstName) .add("secondName", secondName) .toString();}
    • Puzzler Objects.hashCode(a) == a.hashCode() ?Arrays.hashCode(new Object[] { a }) == a.hashCode() ?public static int hashCode(Object a[]) { if (a == null) return 0; int result = 1; for (Object element : a) result = 31 * result + (element == null ? 0 : element.hashCode()); return result;}
    • Compare while equalpublic class PairOfInts { private int first; private int second; public static Comparator<PairOfInts> comparator() { return new Comparator<PairOfInts>() { @Override public int compare(PairOfInts p1, PairOfInts p2) { if (p1.first < p2.first) { return -1; } if (p1.first == p2.first) { if (p1.second < p2.second) { return -1; } if (p1.second == p2.second) { return 0; } } return 1; } }; }}
    • Compare while equalpublic class PairOfInts { private int first; private int second; comparatorInts() { public static Comparator<PairOfInts> comparator() { return new Comparator<PairOfInts>() { @Override public int compare(PairOfInts p1, PairOfInts p2) { int res = Ints.compare(p1.first, p2.first); if (p1.first < p2.first) { if (res == 0) { return -1; } return Ints.compare(p1.second, p2.second); } if (p1.first == p2.first) { return res; if (p1.second < p2.second) { } return -1; }; } } if (p1.second == p2.second) { return 0; } } return 1; } }; }}
    • Compare while equalpublic class PairOfInts { private int first; private int second; public static Comparator<PairOfInts> comparator() { Ordering<PairOfInts> ordering() { comparatorInts() { Ordering.from(new Comparator<PairOfInts>() { return new Comparator<PairOfInts>() { @Override public int compare(PairOfInts p1, PairOfInts p2) { return = Ints.compare(p1.first, p2.first); int resInts.compare(p1.first, p2.first); if (p1.first < p2.first) { } if (res == 0) { return -1; }).compound(new Comparator<PairOfInts>() { p2.second); } return Ints.compare(p1.second, @Override } if (p1.first == p2.first) { public int res; return compare(PairOfInts p1, PairOfInts p2) { if (p1.second < p2.second) { } return Ints.compare(p1.second, p2.second); return -1; }; } } } }); if (p1.second == p2.second) { } return 0; } } return 1; } }; }}
    • Compare while equalpublic class PairOfInts { private int first; private int second; public static Comparator<PairOfInts> comparator() { Ordering<PairOfInts> ordering() { orderingLexicographical() { comparatorInts() { Ordering.<Comparable<?>> natural() Ordering.from(new Comparator<PairOfInts>() { return new Comparator<PairOfInts>() { .lexicographical().onResultOf( @Override public int compare(PairOfIntsIterable<Comparable<?>>>() { new Function<PairOfInts, p1, PairOfInts p2) { return = Ints.compare(p1.first, p2.first); int resInts.compare(p1.first, p2.first); @Override if (p1.first < p2.first) { } if (res == 0) { public Iterable<Comparable<?>> apply(PairOfInts pair) { return -1; }).compound(new Comparator<PairOfInts>() { p2.second); } return Ints.compare(p1.second, return ImmutableList.<Comparable<?>> @Override } of(pair.first, pair.second); if (p1.first == p2.first) { public int res; return compare(PairOfInts p1, PairOfInts p2) { } if (p1.second < p2.second) { } }); return Ints.compare(p1.second, p2.second); return -1; } }; } } } }); if (p1.second == p2.second) { } return 0; } } return 1; } }; }}
    • Compare while equalpublic class PairOfInts { private int first; private int second; public static Comparator<PairOfInts> comparator() { Ordering<PairOfInts> ordering() { orderingLexicographical() { comparatorInts() { Ordering.<Comparable<?>> natural() Ordering.from(new Comparator<PairOfInts>() { return new Comparator<PairOfInts>() { .lexicographical().onResultOf( @Override public int compare(PairOfIntsIterable<Comparable<?>>>() { new Function<PairOfInts, p1, PairOfInts p2) { return = Ints.compare(p1.first, p2.first); int resInts.compare(p1.first, p2.first); @Override if (p1.first < p2.first) { } if (res == 0) { public Iterable<Comparable<?>> apply(PairOfInts pair) { return -1; }).compound(new Comparator<PairOfInts>() { p2.second); } return Ints.compare(p1.second, return ImmutableList.<Comparable<?>> @Override } of(pair.first, pair.second); if (p1.first == p2.first) { public int res; return compare(PairOfInts p1, PairOfInts p2) { } if (p1.second < p2.second) { } }); return Ints.compare(p1.second, p2.second); return -1; } }; } } } }); if (p1.second == p2.second) { } return 0; } } return 1; } }; }}
    • Better Nullspublic class BetterNulls { public static final String DEFAULT = "default"; public String neverNullDefault(String value) { return Objects.firstNonNull(value, DEFAULT); } public String neverNullEmpty(String value) { return Strings.nullToEmpty(value); } public String getValueByKey(String key, Map<String, String> map) { return Functions.forMap(map, DEFAULT).apply(key); } public Optional<String> getValueByKeyOptional(String key, Map<String, String> map) { if (map.containsKey(key)) { return Optional.fromNullable(map.get(key)); } return null; }}
    • Failfast and Join with Joypublic class PreconditionsJoiner { public String joinStrings(Iterable<String> strings) { Preconditions.checkNotNull(strings, "Strings should not be null"); return Joiner.on(", ").skipNulls().join(strings); }}
    • Measure everythingpublic void measureSomething() { Stopwatch stopwatch = new Stopwatch(); for (int i = 0; i < COUNT; i++) { stopwatch.start(); doSomething(); stopwatch.stop(); doUnimpotantThing(); stopwatch.start(); doOtherThing(); stopwatch.stop(); } System.out.println("Average execution time " + stopwatch.elapsedTime(TimeUnit.NANOSECONDS) / COUNT + "ns");}
    • Fast and Immutablepublic List<Integer> createList(int[] elements) { return ImmutableList.copyOf(Ints.asList(elements));}public Map<String, String> createMap() { return ImmutableMap.of("key1", "val1", "key2", "val2");}public Map<String, String> buildMap() { return ImmutableMap.<String, String> builder() .put("key1", "val1") .put("key2", "val2") .build();}
    • More collectionspublic void biMap() { BiMap<Integer, String> biMap = HashBiMap.create(); BiMap<String, Integer> inverseBiMap = biMap.inverse();}public void multimap() { Multimap<Integer, String> multiMap = ArrayListMultimap.create(); multiMap.put(10, "val1"); multiMap.put(10, "val2"); Collection<String> values = multiMap.get(10);}Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();weightedGraph.put(v1, v2, 4.0);weightedGraph.put(v1, v3, 20.0);weightedGraph.put(v2, v3, 5.0);Map<Vertex, Double> row = weightedGraph.row(v1);Map<Vertex, Double> column = weightedGraph.column(v3);
    • Double checked lockingpublic class DCL { private static final Supplier<Object> supplier = Suppliers .memoize(new Supplier<Object>() { @Override public Object get() { return loadResource(); } }); private static Object loadResource() { return new Object(); } public static Object getResource() { return supplier.get(); }}
    • Memoize and Expirepublic class DCLExp { private static final Supplier<Object> supplier = Suppliers .memoizeWithExpiration(new Supplier<Object>() { @Override public Object get() { return loadResource(); } }, 10, TimeUnit.MINUTES); private static Object loadResource() { return new Object(); } public static Object getResource() { return supplier.get(); }}
    • Cachepublic class CacheSample { private final LoadingCache<String, Object> cache = CacheBuilder.newBuilder() .maximumSize(1000) .initialCapacity(100) .concurrencyLevel(10) .expireAfterAccess(30, TimeUnit.SECONDS) .recordStats() .build(new CacheLoader<String, Object>() { @Override public Object load(String key) throws Exception { return loadResourceByKey(key); } }); private Object loadResourceByKey(String key) { return new Object(); } public Object getCachedValue(String key) { return cache.getUnchecked(key); } public CacheStats getStats() { return cache.stats(); }}
    • Functional Idiomspublic static Multiset<Integer> one(Iterable<String> strings) { Function<String, Integer> lengthFunction = new Function<String, Integer>() { @Override public Integer apply(String string) { return string.length(); } }; Predicate<String> allCaps = new Predicate<String>() { @Override public boolean apply(String string) { return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string); } }; return HashMultiset.create(Iterables.transform( Iterables.filter(strings, allCaps), lengthFunction));}
    • Functional Idiomspublic static Multiset<Integer> two(Iterable<String> strings) { return HashMultiset.create( FluentIterable.from(strings) .filter(new Predicate<String>() { @Override public boolean apply(String string) { return CharMatcher.JAVA_UPPER_CASE .matchesAllOf(string); } }) .transform(new Function<String, Integer>() { @Override public Integer apply(String string) { return string.length(); } }));}
    • Functional Idiomspublic static Multiset<Integer> one(Iterable<String> strings) { { three(Iterable<String> strings) Function<String, Integer> lengthFunction = new Function<String, Integer>() { Multiset<Integer> lengths = HashMultiset.create(); for @Override (String string : strings) { public Integer apply(String string) { if (CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string)) { return string.length(); lengths.add(string.length()); } }; } Predicate<String> allCaps = new Predicate<String>() { return lengths;} @Override public boolean apply(String string) { return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string); } }; return HashMultiset.create(Iterables.transform( Iterables.filter(strings, allCaps), lengthFunction));}
    • Catching a Buspublic class BaseEvent {}public class SpecificEvent extends BaseEvent {}public class OtherSpecificEvent extends BaseEvent {}public interface EventListener { void handleSpecific(SpecificEvent event); void handleOtherSpecific(OtherSpecificEvent event);}public class EventListenerAdapter implements EventListener { @Override public void handleSpecific(SpecificEvent event) { } @Override public void handleOtherSpecific(OtherSpecificEvent event) { }}
    • Catching a Buspublic class EventDispatcher { private List<EventListener> listeners = new CopyOnWriteArrayList<EventListener>(); public void addListener(EventListener listener) { listeners.add(listener); } public void removeListener(EventListener listener) { listeners.add(listener); } public void fireSpecific(SpecificEvent event) { for (EventListener listener : listeners) { listener.handleSpecific(event); } } public void fireOtherSpecific(OtherSpecificEvent event) { for (EventListener listener : listeners) { listener.handleOtherSpecific(event); } }}
    • Event Buspublic class BaseEvent {}public class SpecificEvent extends BaseEvent {}public class OtherSpecificEvent extends BaseEvent {}
    • Event Buspublic class EBExample { private static final EventBus eventBus = new EventBus(); public static void main(String[] args) { eventBus.register(new Object() { @Subscribe public void handle(SpecificEvent event) { System.out.println("SpecificEvent: " + event.getClass()); } }); eventBus.register(new Object() { @Subscribe @AllowConcurrentEvents public void handle(BaseEvent event) { System.out.println("BaseEvent: " + event.getClass()); } }); eventBus.post(new SpecificEvent()); }}
    • Even more...• IO• Net• Reflect• Throwables• Hashing• Math• CaseFormat• Concurrency
    • Apache Commons• Just another library• Commons > Guava (BCEL, Fvs, Email)• Guava is more consistent• Guava uses generics• Guava Commons != {}• Guava doesnt solve global tasks• Dont shoot yourself in the foot with Guava
    • Thank you !● Yuriy Krutko (yuri.krutko@odnoklassniki.ru)● Guava (http://code.google.com/p/guava-libraries/)