SlideShare a Scribd company logo
Google Guava


by Yuriy Krutko
Java Developer
Common Myths

Guava is a fruit
Guavas (singular Guava, English pronunciation: /ˈgwɑː.və/[2]) are
plants in the Myrtle family (Myrtaceae) genus Psidium (meaning
"pomegranate" in Latin)




Guava is Google Collections
Guava misuses functional idioms
What's inside
                Strings            Ordering            Throwables


Concurrency
                   Preconditions          Collections


   Reflection                                           EventBus
                           Objects


     Hashing                                  Caches
                    I/O
                               Math

                                               Primitives
          Ranges
Why Guava?
• Guava is a productivity multiplier
• I Could've Invented That
• "Know and use the libraries”
• Don't 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, toString

Code it yourself
Generate using tools (e.g. Eclipse)
Use Guava Objects class
Generated
private String firstName;
private String secondName;

@Override
public String toString() {
    return "PersonGenerated [firstName=" + firstName
            + ", secondName=" + secondName + "]";
}

@Override
public 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
@Override
public 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;
}
Objects
private String firstName;
private String secondName;

@Override
public int hashCode() {
    return Objects.hashCode(firstName, secondName);
}

@Override
public 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;
}

@Override
public 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 equal
public 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 equal
public 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 equal
public 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 equal
public 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 equal
public 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 Nulls
public 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 Joy
public class PreconditionsJoiner {
    public String joinStrings(Iterable<String> strings) {
        Preconditions.checkNotNull(strings, "Strings should not be null");
        return Joiner.on(", ").skipNulls().join(strings);
    }
}
Measure everything
public 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 Immutable
public 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 collections
public 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 locking
public 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 Expire
public 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();
    }
}
Cache
public 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 Idioms
public 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 Idioms
public 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 Idioms
public 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 Bus
public 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 Bus
public 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 Bus
public class BaseEvent {
}
public class SpecificEvent extends BaseEvent {
}

public class OtherSpecificEvent extends BaseEvent {
}
Event Bus
public 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 doesn't solve global tasks
• Don't shoot yourself in the foot with
  Guava
Thank you !
●   Yuriy Krutko (yuri.krutko@odnoklassniki.ru)
●   Guava (http://code.google.com/p/guava-libraries/)

More Related Content

What's hot

Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
Jarek Ratajski
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language Parser
Yodalee
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
Allan Marques Baptista
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
Myeongin Woo
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
Mite Mitreski
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
Tomasz Dziurko
 
Perl
PerlPerl
Generic lazy class
Generic lazy classGeneric lazy class
Generic lazy class
Larry Nung
 
Google guava
Google guavaGoogle guava
Old Oracle Versions
Old Oracle VersionsOld Oracle Versions
Old Oracle VersionsJeffrey Kemp
 
Python functions
Python functionsPython functions
Python functions
ToniyaP1
 
The Ring programming language version 1.2 book - Part 58 of 84
The Ring programming language version 1.2 book - Part 58 of 84The Ring programming language version 1.2 book - Part 58 of 84
The Ring programming language version 1.2 book - Part 58 of 84
Mahmoud Samir Fayed
 
Neuroevolution in Elixir
Neuroevolution in ElixirNeuroevolution in Elixir
Neuroevolution in Elixir
Jeff Smith
 
Elixir: the not-so-hidden path to Erlang
Elixir: the not-so-hidden path to ErlangElixir: the not-so-hidden path to Erlang
Elixir: the not-so-hidden path to Erlang
Laura M. Castro
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8
Jobaer Chowdhury
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
Mite Mitreski
 
Javascript Function
Javascript FunctionJavascript Function
Javascript Function
xxbeta
 

What's hot (19)

Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language Parser
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
 
Perl
PerlPerl
Perl
 
Generic lazy class
Generic lazy classGeneric lazy class
Generic lazy class
 
Google guava
Google guavaGoogle guava
Google guava
 
Old Oracle Versions
Old Oracle VersionsOld Oracle Versions
Old Oracle Versions
 
Python functions
Python functionsPython functions
Python functions
 
The Ring programming language version 1.2 book - Part 58 of 84
The Ring programming language version 1.2 book - Part 58 of 84The Ring programming language version 1.2 book - Part 58 of 84
The Ring programming language version 1.2 book - Part 58 of 84
 
Neuroevolution in Elixir
Neuroevolution in ElixirNeuroevolution in Elixir
Neuroevolution in Elixir
 
Elixir: the not-so-hidden path to Erlang
Elixir: the not-so-hidden path to ErlangElixir: the not-so-hidden path to Erlang
Elixir: the not-so-hidden path to Erlang
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
 
Javascript Function
Javascript FunctionJavascript Function
Javascript Function
 

Similar to Google Guava

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
 
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdfimport java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
Stewart29UReesa
 
Why react matters
Why react mattersWhy react matters
Why react matters
ShihChi Huang
 
Java 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR BeneluxJava 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR Benelux
yohanbeschi
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Codemotion
 
For problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdfFor problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdf
anjandavid
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Fedor Lavrentyev
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
info430661
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
deepakangel
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 
Mixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented language
Mark Needham
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Victor_Cr
 
For the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdfFor the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdf
xlynettalampleyxc
 
NumberList.java (implements the linked list)public class NumberLis.pdf
NumberList.java (implements the linked list)public class NumberLis.pdfNumberList.java (implements the linked list)public class NumberLis.pdf
NumberList.java (implements the linked list)public class NumberLis.pdf
anjanacottonmills
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
arrowmobile
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
Mark Harrison
 
"Java 8, Lambda e la programmazione funzionale" by Theodor Dumitrescu
"Java 8, Lambda e la programmazione funzionale" by Theodor Dumitrescu"Java 8, Lambda e la programmazione funzionale" by Theodor Dumitrescu
"Java 8, Lambda e la programmazione funzionale" by Theodor Dumitrescu
ThinkOpen
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
BTI360
 
Easily mockingdependenciesinc++ 2
Easily mockingdependenciesinc++ 2Easily mockingdependenciesinc++ 2
Easily mockingdependenciesinc++ 2drewz lin
 

Similar to Google Guava (20)

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
 
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdfimport java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
 
Why react matters
Why react mattersWhy react matters
Why react matters
 
Java 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR BeneluxJava 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR Benelux
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
For problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdfFor problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdf
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
 
Sorter
SorterSorter
Sorter
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
Mixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented language
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"
 
For the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdfFor the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdf
 
NumberList.java (implements the linked list)public class NumberLis.pdf
NumberList.java (implements the linked list)public class NumberLis.pdfNumberList.java (implements the linked list)public class NumberLis.pdf
NumberList.java (implements the linked list)public class NumberLis.pdf
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
"Java 8, Lambda e la programmazione funzionale" by Theodor Dumitrescu
"Java 8, Lambda e la programmazione funzionale" by Theodor Dumitrescu"Java 8, Lambda e la programmazione funzionale" by Theodor Dumitrescu
"Java 8, Lambda e la programmazione funzionale" by Theodor Dumitrescu
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Easily mockingdependenciesinc++ 2
Easily mockingdependenciesinc++ 2Easily mockingdependenciesinc++ 2
Easily mockingdependenciesinc++ 2
 

More from Dmitry Buzdin

How Payment Cards Really Work?
How Payment Cards Really Work?How Payment Cards Really Work?
How Payment Cards Really Work?
Dmitry Buzdin
 
Как построить свой фреймворк для автотестов?
Как построить свой фреймворк для автотестов?Как построить свой фреймворк для автотестов?
Как построить свой фреймворк для автотестов?
Dmitry Buzdin
 
How to grow your own Microservice?
How to grow your own Microservice?How to grow your own Microservice?
How to grow your own Microservice?
Dmitry Buzdin
 
How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?
Dmitry Buzdin
 
Delivery Pipeline for Windows Machines
Delivery Pipeline for Windows MachinesDelivery Pipeline for Windows Machines
Delivery Pipeline for Windows Machines
Dmitry Buzdin
 
Big Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop InfrastructureBig Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop Infrastructure
Dmitry Buzdin
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIsDmitry Buzdin
 
Архитектура Ленты на Одноклассниках
Архитектура Ленты на ОдноклассникахАрхитектура Ленты на Одноклассниках
Архитектура Ленты на ОдноклассникахDmitry Buzdin
 
Riding Redis @ask.fm
Riding Redis @ask.fmRiding Redis @ask.fm
Riding Redis @ask.fmDmitry Buzdin
 
Rubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part IIRubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part IIDmitry Buzdin
 
Rubylight Pattern-Matching Solutions
Rubylight Pattern-Matching SolutionsRubylight Pattern-Matching Solutions
Rubylight Pattern-Matching SolutionsDmitry Buzdin
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional ProgrammingDmitry Buzdin
 
Rubylight programming contest
Rubylight programming contestRubylight programming contest
Rubylight programming contestDmitry Buzdin
 
Continuous Delivery
Continuous Delivery Continuous Delivery
Continuous Delivery Dmitry Buzdin
 
Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOpsDmitry Buzdin
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump AnalysisDmitry Buzdin
 

More from Dmitry Buzdin (20)

How Payment Cards Really Work?
How Payment Cards Really Work?How Payment Cards Really Work?
How Payment Cards Really Work?
 
Как построить свой фреймворк для автотестов?
Как построить свой фреймворк для автотестов?Как построить свой фреймворк для автотестов?
Как построить свой фреймворк для автотестов?
 
How to grow your own Microservice?
How to grow your own Microservice?How to grow your own Microservice?
How to grow your own Microservice?
 
How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?
 
Delivery Pipeline for Windows Machines
Delivery Pipeline for Windows MachinesDelivery Pipeline for Windows Machines
Delivery Pipeline for Windows Machines
 
Big Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop InfrastructureBig Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop Infrastructure
 
JOOQ and Flyway
JOOQ and FlywayJOOQ and Flyway
JOOQ and Flyway
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
 
Whats New in Java 8
Whats New in Java 8Whats New in Java 8
Whats New in Java 8
 
Архитектура Ленты на Одноклассниках
Архитектура Ленты на ОдноклассникахАрхитектура Ленты на Одноклассниках
Архитектура Ленты на Одноклассниках
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
Riding Redis @ask.fm
Riding Redis @ask.fmRiding Redis @ask.fm
Riding Redis @ask.fm
 
Rubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part IIRubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part II
 
Rubylight Pattern-Matching Solutions
Rubylight Pattern-Matching SolutionsRubylight Pattern-Matching Solutions
Rubylight Pattern-Matching Solutions
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
 
Rubylight programming contest
Rubylight programming contestRubylight programming contest
Rubylight programming contest
 
Continuous Delivery
Continuous Delivery Continuous Delivery
Continuous Delivery
 
Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOps
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 

Recently uploaded

Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 

Recently uploaded (20)

Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 

Google Guava

  • 1. Google Guava by Yuriy Krutko Java Developer
  • 2. Common Myths Guava is a fruit Guavas (singular Guava, English pronunciation: /ˈgwɑː.və/[2]) are plants in the Myrtle family (Myrtaceae) genus Psidium (meaning "pomegranate" in Latin) Guava is Google Collections Guava misuses functional idioms
  • 3. What's inside Strings Ordering Throwables Concurrency Preconditions Collections Reflection EventBus Objects Hashing Caches I/O Math Primitives Ranges
  • 4. Why Guava? • Guava is a productivity multiplier • I Could've Invented That • "Know and use the libraries” • Don't reinvent the wheel. • Could not be included into Java API
  • 5. 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.
  • 6. equals, hashCode, toString Code it yourself Generate using tools (e.g. Eclipse) Use Guava Objects class
  • 7. Generated private String firstName; private String secondName; @Override public String toString() { return "PersonGenerated [firstName=" + firstName + ", secondName=" + secondName + "]"; } @Override public 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; }
  • 8. Generate @Override public 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; }
  • 9. Objects private String firstName; private String secondName; @Override public int hashCode() { return Objects.hashCode(firstName, secondName); } @Override public 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; } @Override public String toString() { return Objects.toStringHelper(this) .add("firstName", firstName) .add("secondName", secondName) .toString(); }
  • 10. 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; }
  • 11. Compare while equal public 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; } }; } }
  • 12. Compare while equal public 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; } }; } }
  • 13. Compare while equal public 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; } }; } }
  • 14. Compare while equal public 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; } }; } }
  • 15. Compare while equal public 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; } }; } }
  • 16. Better Nulls public 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; } }
  • 17. Failfast and Join with Joy public class PreconditionsJoiner { public String joinStrings(Iterable<String> strings) { Preconditions.checkNotNull(strings, "Strings should not be null"); return Joiner.on(", ").skipNulls().join(strings); } }
  • 18. Measure everything public 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"); }
  • 19. Fast and Immutable public 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(); }
  • 20. More collections public 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);
  • 21. Double checked locking public 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(); } }
  • 22. Memoize and Expire public 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(); } }
  • 23. Cache public 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(); } }
  • 24. Functional Idioms public 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)); }
  • 25. Functional Idioms public 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(); } })); }
  • 26. Functional Idioms public 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)); }
  • 27. Catching a Bus public 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) { } }
  • 28. Catching a Bus public 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); } } }
  • 29. Event Bus public class BaseEvent { } public class SpecificEvent extends BaseEvent { } public class OtherSpecificEvent extends BaseEvent { }
  • 30. Event Bus public 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()); } }
  • 31. Even more... • IO • Net • Reflect • Throwables • Hashing • Math • CaseFormat • Concurrency
  • 32. Apache Commons • Just another library • Commons > Guava (BCEL, Fvs, Email) • Guava is more consistent • Guava uses generics • Guava Commons != {} • Guava doesn't solve global tasks • Don't shoot yourself in the foot with Guava
  • 33. Thank you ! ● Yuriy Krutko (yuri.krutko@odnoklassniki.ru) ● Guava (http://code.google.com/p/guava-libraries/)