SlideShare una empresa de Scribd logo
1 de 47
Descargar para leer sin conexión
The Google Collections
    Library (for Java)
  Kevin Bourrillion, Google, Inc.
     SV-GTUG 2008-08-06
In a nutshell

  An open-source (Apache 2) library
  http://google-collections.googlecode.com
  Requires JDK 1.5
  Pre-release snapshot available, 0.9 release coming
  Not API-frozen until release 1.0 (no timetable)
  But is widely used in production at Google
  Developers: Jared Levy and myself, with a lot of help from
  our friends
Overview

1.   In a nutshell
2.   Immutable Collections
3.   Multisets
4.   Multimaps
5.   Other new types/impls
6.   Static utilities
7.   Other stuff
8.   Q&A

Questions also welcome throughout!
Immutable Collections

  JDK has Collections.unmodifiableFoo() wrappers
  Unmodifiable = you can't change it
  Immutable = it can never change, no matter what
    (externally-visible state, that is)
  Immutability is tasty!
    See Effective Java for some of the many reasons
Immutable Collections (2)

We provide:

   ImmutableList
   ImmutableSet
   ImmutableSortedSet
   ImmutableMap
   ImmutableSortedMap (one day)

Brand-new, standalone implementations
Immutable vs. unmodifiable

The JDK wrappers are still useful for unmodifiable views of
changing data. But for most purposes, use ours:

   Immutability guarantee!
   Very easy to use
       (we'll show you on the following slides)
   Slightly faster
   Use less memory
       Sometimes far less (ImmutableSet, factor of 2-3x)
Constant sets: Before, v1

public static final Set<Integer> LUCKY_NUMBERS;
static {
  Set<Integer> set = new LinkedHashSet<Integer>();
  set.add(4);
  set.add(8);
  set.add(15);
  set.add(16);
  set.add(23);
  set.add(42);
  LUCKY_NUMBERS = Collections.unmodifiableSet(set);
}
Constant sets: Before, v2

public static final Set<Integer> LUCKY_NUMBERS
    = Collections.unmodifiableSet(
        new LinkedHashSet<Integer>(
            Arrays.asList(4, 8, 15, 16, 23, 42)));

   A little nicer.
   But uses four different classes! Something's weird.
Constant sets: After

public static final ImmutableSet<Integer> LUCKY_NUMBERS
    = ImmutableSet.of(4, 8, 15, 16, 23, 42);

   Now we just say exactly what we mean.
   And get performance benefits as well!
   We're using just one class (it implements Set)
   of() method name inspired by java.util.EnumSet
Constant maps: Before

public static final Map<String, Integer> ENGLISH_TO_INT;
static {
  Map<String, Integer> map
      = new LinkedHashMap<String, Integer>();
  map.put(quot;fourquot;, 4);
  map.put(quot;eightquot;, 8);
  map.put(quot;fifteenquot;, 15);
  map.put(quot;sixteenquot;, 16);
  map.put(quot;twenty-threequot;, 23);
  map.put(quot;forty-twoquot;, 42);
  ENGLISH_TO_INT = Collections.unmodifiableMap(map);
}
Constant maps: After

public static final ImmutableMap<String, Integer>
    ENGLISH_TO_INT = ImmutableMap
        .with(quot;fourquot;, 4)
        .with(quot;eightquot;, 8)
        .with(quot;fifteenquot;, 15)
        .with(quot;sixteenquot;, 16)
        .with(quot;twenty-threequot;, 23)
        .with(quot;forty-twoquot;, 42)
        .build();
Defensive copies: Before

private final Set<Integer> luckyNumbers;
public Dharma(Set<Integer> numbers) {
  luckyNumbers = Collections.unmodifiableSet(
      new LinkedHashSet<Integer>(numbers));
}
public Set<Integer> getLuckyNumbers() {
  return luckyNumbers;
}

   Copy on the way in
   Wrap in unmodifiable on the way in or the way out
Defensive copies: After

private final ImmutableSet<Integer> luckyNumbers;
public Dharma(Set<Integer> numbers) {
  luckyNumbers = ImmutableSet.copyOf(numbers);
}
public ImmutableSet<Integer> getLuckyNumbers() {
  return luckyNumbers;
}

   Type, not just implementation
   What if you forget?
   Note: copyOf() cheats!
Immutable Collections: more examples

Sets:
static final ImmutableSet<Country> BETA_COUNTRIES = ...

    ImmutableSet.of();
    ImmutableSet.of(a);
    ImmutableSet.of(a, b, c);
    ImmutableSet.copyOf(someIterator);
    ImmutableSet.copyOf(someIterable);

Small maps:

static final ImmutableMap<Integer, String> MAP
    = ImmutableMap.of(1, quot;onequot;, 2, quot;twoquot;);
Immutable Collections: caveats

  These collections are null-hostile
     In 95%+ of cases, this is what you want
     In other cases, fine workarounds exist
     This aligns with recent work on JDK collections
     (and it's a little faster this way)
     (and keeps the implementation simpler)


  Mutable elements can sometimes lead to confusion
    The resulting object won't be quot;deeply immutablequot;
Immutable Collections: summary

 In the past, we'd ask, quot;does this need to be immutable?quot;
 Now we ask, quot;does it need to be mutable?quot;
Overview

1.   In a nutshell
2.   Immutable Collections
3.   Multisets
4.   Multimaps
5.   Other new types/impls
6.   Static utilities
7.   Other stuff
8.   Q&A

Questions also welcome throughout!
Collection behavior

When you have quot;a bunch of foosquot;, use a Collection -- but what
kind?

   Can it have duplicates?
   Is ordering significant? (for equals())
   Iteration order
       insertion-ordered? comparator-ordered? user-ordered?
       something else well-defined?
       or it just doesn't matter?

In general, the first two determine the interface type, and the
third tends to influence your choice of implementation.
List vs. Set

Set: unordered equality, no duplicates.
List: ordered equality, can have duplicates.

             Ordered?
             Y      N
    Dups? +------+-----+
     Y    | List | ? |
          +------+-----+
     N    |    ? | Set |
          +------+-----+
List vs. Set... and then some

Multiset: unordered equality, can have duplicates.

                       Ordered?
                Y           N
 Dups?    +------------+---------+
   Y      |    List    |Multiset!|
          +------------+---------+
    N     |(UniqueList)|   Set   |
          +------------+---------+

(UniqueList might appear in our library one day.)
When to use a Multiset?

   quot;I kinda want a Set except I can have duplicatesquot;
       card game example
       changing to List sacrifices contains() performance
   quot;Are these Lists equal, ignoring order?quot;
       write a utility method for this?
   Histograms
       quot;What distinct tags am I using on my blog, and how
       many times do I use each one?quot;

Multiset performance varies by the number of distinct elements,
not total size.
Multiset: tags example, before

Map<String, Integer> tags
    = new HashMap<String, Integer>();
for (BlogPost post : getAllBlogPosts()) {
  for (String tag : post.getTags()) {
    int value = tags.containsKey(tag) ? tags.get(tag) : 0;
    tags.put(tag, value + 1);
  }
}

   distinct tags: tags.keySet()
   count for quot;javaquot; tag: tags.containsKey(quot;javaquot;) ? tags.get
   (quot;javaquot;) : 0;
   total count: // oh crap...
Multiset: tags example, after

Multiset<String> tags = HashMultiset.create();
for (BlogPost post : getAllBlogPosts()) {
  tags.addAll(post.getTags());
}



               (... this space intentionally left blank ...)




   distinct tags: tags.elementSet();
   count for quot;javaquot; tag: tags.count(quot;javaquot;);
   total count: tags.size();
Multiset: tags example, after after

  What if you need to remove/decrement?
     Don't accidentally go negative
     Don't forget to prune!
     (Or just use a Multiset.)
  What about concurrency?
     Lock the entire map just to add one tag?
     (Or just use our ConcurrentMultiset.)
  When you use a powerful library, your code can easily
  evolve.
Multiset API

Everything from Collection, plus:

  int count(Object element);

  int add(E element, int occurrences);

  boolean remove(Object element, int occurrences);

  int setCount(E element, int newCount);

  boolean setCount(E e, int oldCount, int newCount);
Multiset implementations

  ImmutableMultiset
  HashMultiset
  LinkedHashMultiset
  TreeMultiset
  EnumMultiset
  ConcurrentMultiset
Overview

1.   In a nutshell
2.   Immutable Collections
3.   Multisets
4.   Multimaps
5.   Other new types/impls
6.   Static utilities
7.   Other stuff
8.   Q&A

Questions also welcome throughout!
Multimaps, before

Ever done this?

Map<Salesperson, List<Sale>> map
    = new HashMap<Salesperson, List<Sale>>();

public void makeSale(Salesperson salesPerson, Sale sale) {
  List<Sale> sales = map.get(salesPerson);
  if (sales == null) {
    sales = new ArrayList<Sale>();
    map.put(salesPerson, sales);
  }
  sales.add(sale);
}
Multimaps, after

Would you rather do this?

Multimap<Salesperson, Sale> multimap
    = ArrayListMultimap.create();

public void makeSale(Salesperson salesPerson, Sale sale) {
  multimap.put(salesPerson, sale);
}

The code on the last slide is
   Verbose
   Bug-prone
   Limited in functionality
   Using the wrong abstraction
About Multimaps

A collection of key-value pairs (entries), like a Map, except that
keys don't have to be unique.

 {a=1, a=2, b=3, c=4, c=5, c=6}

multimap.get(key) returns a modifiable Collection view of the
values associated with that key.

Sometimes you want to think of it as a Map<K, Collection<V>>
-- use the asMap() view:

 {a=[1, 2], b=[3], c=[4, 5, 6]}
Multimap subtypes

   ListMultimap: the get() view implements List
       preserves the ordering of entries per key; can have
       duplicate entries
   SetMultimap: the get() view implements Set
       no duplicate entries, ordering of entries is impl-
       dependent
   SortedSetMultimap: the get() view implements SortedSet
       you get the idea

Hmm... sounds a lot like a plain old Map<K, Collection<V>>?

But wait...
Multimap example 2, before

Now we want to find the biggest Sale. Without Multimap:
public Sale getBiggestSale() {
  Sale biggestSale = null;
  for (List<Sale> sales : map.values()) {
    Sale myBiggestSale = Collections.max(sales,
        SALE_CHARGE_COMPARATOR);
    if (biggestSale == null ||
        myBiggestSale.getCharge() > biggestSale().getCharge()) {
      biggestSale = myBiggestSale;
    }
  }
  return biggestSale;
}
Multimap example 2, after

With Multimap:
public Sale getBiggestSale() {
  return Collections.max(multimap.values(),
      SALE_CHARGE_COMPARATOR);
}

View collections are very powerful. Multimap has six: get(),
keys(), keySet(), values(), entries(), asMap().
Multimap vs. Map

 Most Map methods are identical on Multimap:
    size(), isEmpty()
    containsKey(), containsValue()
    put(), putAll()
    clear()
    values()
 The others have analogues
    get() returns Collection<V> instead of V
    remove(K) becomes remove(K,V) and removeAll(K)
    keySet() becomes keys() (well, and keySet())
    entrySet() becomes entries()
 And Multimap has a few new things
    containsEntry(), replaceValues()
Multimap implementations

 ImmutableMultimap
 ArrayListMultimap
 HashMultimap
 LinkedHashMultimap
 TreeMultimap
Overview

1.   In a nutshell
2.   Immutable Collections
3.   Multisets
4.   Multimaps
5.   Other new types/impls
6.   Static utilities
7.   Other stuff
8.   Q&A

Questions also welcome throughout!
BiMap

  aka unique-valued map, it guarantees its values are unique,
  as well as its keys
  Has an inverse() view, which is another BiMap
     bimap.inverse().inverse() == bimap
  Stop creating two separate forward and backward Maps!
     Let us do that for you.

Implementations:
   ImmutableBiMap
   HashBiMap
   EnumBiMap
ReferenceMap

 (If you haven't used weak or soft references, take a one-
 minute nap.)
 A generalization of java.util.WeakHashMap
 Nine possible combinations:
      strong, weak or soft keys
      strong, weak or soft values
 Fully concurrent
      implements ConcurrentMap
      cleanup happens in GC thread
 Isn't yet as fast as it could be, but we use it anyway
Ordering class

Comparator is easy to implement, but a pain to use.
Ordering is Comparator++ (or RichComparator).

Ordering<String> caseless = Ordering.forComparator(
    String.CASE_INSENSITIVE_ORDER);

Now you have tasty methods like min(Iterable), max(Iterable),
isIncreasing(Iterable), sortedCopy(Iterable), reverse()...
Overview

1.   In a nutshell
2.   Immutable Collections
3.   Multisets
4.   Multimaps
5.   Other new types/impls
6.   Static utilities
7.   Other stuff
8.   Q&A

Questions also welcome throughout!
Static factory methods

   We has them.
   Rather than asking you to type

Multimap<String, Class<? extends Handler>> handlers =
  new ArrayListMultimap<String, Class<? extends
Handler>>();

   you type

Multimap<String, Class<? extends Handler>> handlers =
  ArrayListMultimap.create();

   We provide these for JDK collections too, in classes called
   Lists, Sets and Maps.
   With overloads to accept Iterables to copy elements from
Working with Itera*s

  Collection is a good abstraction when all your data is in
  memory
  Sometimes you want to process large amounts of data in a
  single pass
  Implementing Collection is possible but cumbersome, and
  won't behave nicely
  Iterator and Iterable are often all you need
  Our methods accept Iterator and Iterable whenever
  practical
  And ...
quot;Iteratorsquot; and quot;Iterablesquot; classes

These classes have parallel APIs, one for Iterator and the other
for Iterable.

  Iterable transform(Iterable, Function)*
  Iterable filter(Iterable, Predicate)*
  T find(Iterable<T>, Predicate)
  Iterable concat(Iterable<Iterable>)
  Iterable cycle(Iterable)
  T getOnlyElement(Iterable<T>)
  Iterable<T> reverse(List<T>)

These methods are LAZY!

*No, this doesn't make Java into an FP language.
Overview

1.   In a nutshell
2.   Immutable Collections
3.   Multisets
4.   Multimaps
5.   Other new types/impls
6.   Static utilities
7.   Other stuff
8.   Q&A

Questions also welcome throughout!
What we're not telling you about

  Forwarding collections
  Constrained collections
  Precondition checking
  Union/intersection/difference for Sets
  Multimaps.index() and Maps.uniqueIndex()
  ClassToInstanceMap
  ObjectArrays utilities
  AbstractIterator and PeekingIterator
  Join.join()
  and more
How do we test this stuff?

We have over 25,000 unit tests. How?
return new SetTestSuiteBuilder()
  .named(quot;Sets.filterquot;)
  .withFeatures(GENERAL_PURPOSE, ALLOWS_NULL_VALUES,
                 KNOWN_ORDER, CollectionSize.ANY)
  .using(new TestStringCollectionGenerator() {
       public Set<String> create(String[] elements) {
         return Sets.filter(...);
       }
    })
  .createTestSuite();


   Googlers George van den Driessche and Chris Povirk
   We'll open-source this framework too
   Several JDK collections don't pass all its tests!
Q&A

http://google-collections.googlecode.com

Más contenido relacionado

La actualidad más candente

Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidJordi Gerona
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overviewSteve Min
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee confIgor Anishchenko
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real Worldosfameron
 
java 8 Hands on Workshop
java 8 Hands on Workshopjava 8 Hands on Workshop
java 8 Hands on WorkshopJeanne Boyarsky
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic OperationsWai Nwe Tun
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Paige Bailey
 
Scala101, first steps with Scala
Scala101, first steps with ScalaScala101, first steps with Scala
Scala101, first steps with ScalaGiampaolo Trapasso
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of AtrocityMichael Pirnat
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introductiongosain20
 

La actualidad más candente (20)

Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
 
java 8 Hands on Workshop
java 8 Hands on Workshopjava 8 Hands on Workshop
java 8 Hands on Workshop
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
 
Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic Operations
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Eta
EtaEta
Eta
 
Scala101, first steps with Scala
Scala101, first steps with ScalaScala101, first steps with Scala
Scala101, first steps with Scala
 
Kotlin standard
Kotlin standardKotlin standard
Kotlin standard
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
 

Destacado

Show 68 PERQ INTERVIEW w/ Scott Hill & Andy Medley
Show 68 PERQ INTERVIEW w/ Scott Hill & Andy MedleyShow 68 PERQ INTERVIEW w/ Scott Hill & Andy Medley
Show 68 PERQ INTERVIEW w/ Scott Hill & Andy MedleyErin Sparks
 
Hotel: La Bastide de Tourtour****
Hotel: La Bastide de Tourtour****Hotel: La Bastide de Tourtour****
Hotel: La Bastide de Tourtour****odelia
 
Marketing During Recession, Pham Viet Anh
Marketing During Recession, Pham Viet AnhMarketing During Recession, Pham Viet Anh
Marketing During Recession, Pham Viet Anhphamvietanh
 
FRE 6431s Project
FRE 6431s ProjectFRE 6431s Project
FRE 6431s Projectmalshetwey
 
April Vacation
April VacationApril Vacation
April VacationDBrandon69
 
Flip4 mac wmv user guide
Flip4 mac wmv user guideFlip4 mac wmv user guide
Flip4 mac wmv user guidemmoreno123
 
Albeniz Tango Op.165 N°2 (Violin And Piano)
Albeniz  Tango Op.165 N°2 (Violin And Piano)Albeniz  Tango Op.165 N°2 (Violin And Piano)
Albeniz Tango Op.165 N°2 (Violin And Piano)HOME
 
Zach massad portf pt 2
Zach massad portf pt 2Zach massad portf pt 2
Zach massad portf pt 2Zach Massad
 
Getting published – how the library can help
Getting published – how the library can helpGetting published – how the library can help
Getting published – how the library can helpbradscifi
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfoliodklawson
 
M. VRUBEL
M. VRUBELM. VRUBEL
M. VRUBELlensu
 
醫學的無限(線)未來
醫學的無限(線)未來醫學的無限(線)未來
醫學的無限(線)未來David Yeh
 
Web Hooks And The Programmable World Of Tomorrow
Web Hooks And The Programmable World Of TomorrowWeb Hooks And The Programmable World Of Tomorrow
Web Hooks And The Programmable World Of TomorrowGoogleTecTalks
 
100 Obras Essenciais
100 Obras Essenciais100 Obras Essenciais
100 Obras EssenciaisHOME
 
Teoria Musical
Teoria  MusicalTeoria  Musical
Teoria MusicalHOME
 
Post Settlement Pitfalls 2009
Post Settlement Pitfalls 2009Post Settlement Pitfalls 2009
Post Settlement Pitfalls 2009bigfaz2009
 
Abb Tech Conference Program
Abb Tech Conference ProgramAbb Tech Conference Program
Abb Tech Conference Programrwaldo
 

Destacado (20)

Show 68 PERQ INTERVIEW w/ Scott Hill & Andy Medley
Show 68 PERQ INTERVIEW w/ Scott Hill & Andy MedleyShow 68 PERQ INTERVIEW w/ Scott Hill & Andy Medley
Show 68 PERQ INTERVIEW w/ Scott Hill & Andy Medley
 
Hotel: La Bastide de Tourtour****
Hotel: La Bastide de Tourtour****Hotel: La Bastide de Tourtour****
Hotel: La Bastide de Tourtour****
 
Marketing During Recession, Pham Viet Anh
Marketing During Recession, Pham Viet AnhMarketing During Recession, Pham Viet Anh
Marketing During Recession, Pham Viet Anh
 
FRE 6431s Project
FRE 6431s ProjectFRE 6431s Project
FRE 6431s Project
 
April Vacation
April VacationApril Vacation
April Vacation
 
Flip4 mac wmv user guide
Flip4 mac wmv user guideFlip4 mac wmv user guide
Flip4 mac wmv user guide
 
Albeniz Tango Op.165 N°2 (Violin And Piano)
Albeniz  Tango Op.165 N°2 (Violin And Piano)Albeniz  Tango Op.165 N°2 (Violin And Piano)
Albeniz Tango Op.165 N°2 (Violin And Piano)
 
Zach massad portf pt 2
Zach massad portf pt 2Zach massad portf pt 2
Zach massad portf pt 2
 
Getting published – how the library can help
Getting published – how the library can helpGetting published – how the library can help
Getting published – how the library can help
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
 
123
123123
123
 
M. VRUBEL
M. VRUBELM. VRUBEL
M. VRUBEL
 
醫學的無限(線)未來
醫學的無限(線)未來醫學的無限(線)未來
醫學的無限(線)未來
 
Web Hooks And The Programmable World Of Tomorrow
Web Hooks And The Programmable World Of TomorrowWeb Hooks And The Programmable World Of Tomorrow
Web Hooks And The Programmable World Of Tomorrow
 
Benim IçIn Efes
Benim IçIn EfesBenim IçIn Efes
Benim IçIn Efes
 
100 Obras Essenciais
100 Obras Essenciais100 Obras Essenciais
100 Obras Essenciais
 
Indian Rupee Symbol Design
Indian Rupee Symbol DesignIndian Rupee Symbol Design
Indian Rupee Symbol Design
 
Teoria Musical
Teoria  MusicalTeoria  Musical
Teoria Musical
 
Post Settlement Pitfalls 2009
Post Settlement Pitfalls 2009Post Settlement Pitfalls 2009
Post Settlement Pitfalls 2009
 
Abb Tech Conference Program
Abb Tech Conference ProgramAbb Tech Conference Program
Abb Tech Conference Program
 

Similar a Using The Google Collections Library For Java

Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Effective Java - Still Effective After All These Years
Effective Java - Still Effective After All These YearsEffective Java - Still Effective After All These Years
Effective Java - Still Effective After All These YearsMarakana Inc.
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxAbhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
 
Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Peter Antman
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptMohd Saeed
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5ecomputernotes
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Featurestarun308
 
Computer notes - Hashing
Computer notes - HashingComputer notes - Hashing
Computer notes - Hashingecomputernotes
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Codemotion
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasicswebuploader
 
computer notes - Data Structures - 35
computer notes - Data Structures - 35computer notes - Data Structures - 35
computer notes - Data Structures - 35ecomputernotes
 

Similar a Using The Google Collections Library For Java (20)

Java Generics
Java GenericsJava Generics
Java Generics
 
Effective Java - Still Effective After All These Years
Effective Java - Still Effective After All These YearsEffective Java - Still Effective After All These Years
Effective Java - Still Effective After All These Years
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Collections
CollectionsCollections
Collections
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascript
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Computer notes - Hashing
Computer notes - HashingComputer notes - Hashing
Computer notes - Hashing
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
 
Lazy java
Lazy javaLazy java
Lazy java
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
 
computer notes - Data Structures - 35
computer notes - Data Structures - 35computer notes - Data Structures - 35
computer notes - Data Structures - 35
 

Más de GoogleTecTalks

Voice Browsing And Multimodal Interaction In 2009
Voice Browsing And Multimodal Interaction In 2009Voice Browsing And Multimodal Interaction In 2009
Voice Browsing And Multimodal Interaction In 2009GoogleTecTalks
 
V Code And V Data Illustrating A New Framework For Supporting The Video Annot...
V Code And V Data Illustrating A New Framework For Supporting The Video Annot...V Code And V Data Illustrating A New Framework For Supporting The Video Annot...
V Code And V Data Illustrating A New Framework For Supporting The Video Annot...GoogleTecTalks
 
New Media Mavericks Will The Revolution Be Spidered
New Media Mavericks Will The Revolution Be SpideredNew Media Mavericks Will The Revolution Be Spidered
New Media Mavericks Will The Revolution Be SpideredGoogleTecTalks
 
Performance Improvements In Browsers
Performance Improvements In BrowsersPerformance Improvements In Browsers
Performance Improvements In BrowsersGoogleTecTalks
 
13353102 Putting The Fun In Functional Applying Game Mechanics To Functional ...
13353102 Putting The Fun In Functional Applying Game Mechanics To Functional ...13353102 Putting The Fun In Functional Applying Game Mechanics To Functional ...
13353102 Putting The Fun In Functional Applying Game Mechanics To Functional ...GoogleTecTalks
 
Black Cloud Patterns Toward The Future
Black Cloud Patterns Toward The FutureBlack Cloud Patterns Toward The Future
Black Cloud Patterns Toward The FutureGoogleTecTalks
 
Advanced Ruby Scripting For Sketch Up
Advanced Ruby Scripting For Sketch UpAdvanced Ruby Scripting For Sketch Up
Advanced Ruby Scripting For Sketch UpGoogleTecTalks
 
An Introduction To Android
An Introduction To AndroidAn Introduction To Android
An Introduction To AndroidGoogleTecTalks
 
Advanced Gadget And Ui Development Using Googles Ajax Ap Is
Advanced Gadget And Ui Development Using Googles Ajax Ap IsAdvanced Gadget And Ui Development Using Googles Ajax Ap Is
Advanced Gadget And Ui Development Using Googles Ajax Ap IsGoogleTecTalks
 
A World Beyond Ajax Accessing Googles Ap Is From Flash And Non Java Script En...
A World Beyond Ajax Accessing Googles Ap Is From Flash And Non Java Script En...A World Beyond Ajax Accessing Googles Ap Is From Flash And Non Java Script En...
A World Beyond Ajax Accessing Googles Ap Is From Flash And Non Java Script En...GoogleTecTalks
 
Keynote Client Connectivity And The Cloud
Keynote Client Connectivity And The CloudKeynote Client Connectivity And The Cloud
Keynote Client Connectivity And The CloudGoogleTecTalks
 

Más de GoogleTecTalks (12)

Voice Browsing And Multimodal Interaction In 2009
Voice Browsing And Multimodal Interaction In 2009Voice Browsing And Multimodal Interaction In 2009
Voice Browsing And Multimodal Interaction In 2009
 
V Code And V Data Illustrating A New Framework For Supporting The Video Annot...
V Code And V Data Illustrating A New Framework For Supporting The Video Annot...V Code And V Data Illustrating A New Framework For Supporting The Video Annot...
V Code And V Data Illustrating A New Framework For Supporting The Video Annot...
 
New Media Mavericks Will The Revolution Be Spidered
New Media Mavericks Will The Revolution Be SpideredNew Media Mavericks Will The Revolution Be Spidered
New Media Mavericks Will The Revolution Be Spidered
 
Performance Improvements In Browsers
Performance Improvements In BrowsersPerformance Improvements In Browsers
Performance Improvements In Browsers
 
13353102 Putting The Fun In Functional Applying Game Mechanics To Functional ...
13353102 Putting The Fun In Functional Applying Game Mechanics To Functional ...13353102 Putting The Fun In Functional Applying Game Mechanics To Functional ...
13353102 Putting The Fun In Functional Applying Game Mechanics To Functional ...
 
Black Cloud Patterns Toward The Future
Black Cloud Patterns Toward The FutureBlack Cloud Patterns Toward The Future
Black Cloud Patterns Toward The Future
 
Advanced Ruby Scripting For Sketch Up
Advanced Ruby Scripting For Sketch UpAdvanced Ruby Scripting For Sketch Up
Advanced Ruby Scripting For Sketch Up
 
An Introduction To Android
An Introduction To AndroidAn Introduction To Android
An Introduction To Android
 
Advanced Gadget And Ui Development Using Googles Ajax Ap Is
Advanced Gadget And Ui Development Using Googles Ajax Ap IsAdvanced Gadget And Ui Development Using Googles Ajax Ap Is
Advanced Gadget And Ui Development Using Googles Ajax Ap Is
 
Advanced Kml
Advanced KmlAdvanced Kml
Advanced Kml
 
A World Beyond Ajax Accessing Googles Ap Is From Flash And Non Java Script En...
A World Beyond Ajax Accessing Googles Ap Is From Flash And Non Java Script En...A World Beyond Ajax Accessing Googles Ap Is From Flash And Non Java Script En...
A World Beyond Ajax Accessing Googles Ap Is From Flash And Non Java Script En...
 
Keynote Client Connectivity And The Cloud
Keynote Client Connectivity And The CloudKeynote Client Connectivity And The Cloud
Keynote Client Connectivity And The Cloud
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Using The Google Collections Library For Java

  • 1. The Google Collections Library (for Java) Kevin Bourrillion, Google, Inc. SV-GTUG 2008-08-06
  • 2. In a nutshell An open-source (Apache 2) library http://google-collections.googlecode.com Requires JDK 1.5 Pre-release snapshot available, 0.9 release coming Not API-frozen until release 1.0 (no timetable) But is widely used in production at Google Developers: Jared Levy and myself, with a lot of help from our friends
  • 3. Overview 1. In a nutshell 2. Immutable Collections 3. Multisets 4. Multimaps 5. Other new types/impls 6. Static utilities 7. Other stuff 8. Q&A Questions also welcome throughout!
  • 4. Immutable Collections JDK has Collections.unmodifiableFoo() wrappers Unmodifiable = you can't change it Immutable = it can never change, no matter what (externally-visible state, that is) Immutability is tasty! See Effective Java for some of the many reasons
  • 5. Immutable Collections (2) We provide: ImmutableList ImmutableSet ImmutableSortedSet ImmutableMap ImmutableSortedMap (one day) Brand-new, standalone implementations
  • 6. Immutable vs. unmodifiable The JDK wrappers are still useful for unmodifiable views of changing data. But for most purposes, use ours: Immutability guarantee! Very easy to use (we'll show you on the following slides) Slightly faster Use less memory Sometimes far less (ImmutableSet, factor of 2-3x)
  • 7. Constant sets: Before, v1 public static final Set<Integer> LUCKY_NUMBERS; static { Set<Integer> set = new LinkedHashSet<Integer>(); set.add(4); set.add(8); set.add(15); set.add(16); set.add(23); set.add(42); LUCKY_NUMBERS = Collections.unmodifiableSet(set); }
  • 8. Constant sets: Before, v2 public static final Set<Integer> LUCKY_NUMBERS = Collections.unmodifiableSet( new LinkedHashSet<Integer>( Arrays.asList(4, 8, 15, 16, 23, 42))); A little nicer. But uses four different classes! Something's weird.
  • 9. Constant sets: After public static final ImmutableSet<Integer> LUCKY_NUMBERS = ImmutableSet.of(4, 8, 15, 16, 23, 42); Now we just say exactly what we mean. And get performance benefits as well! We're using just one class (it implements Set) of() method name inspired by java.util.EnumSet
  • 10. Constant maps: Before public static final Map<String, Integer> ENGLISH_TO_INT; static { Map<String, Integer> map = new LinkedHashMap<String, Integer>(); map.put(quot;fourquot;, 4); map.put(quot;eightquot;, 8); map.put(quot;fifteenquot;, 15); map.put(quot;sixteenquot;, 16); map.put(quot;twenty-threequot;, 23); map.put(quot;forty-twoquot;, 42); ENGLISH_TO_INT = Collections.unmodifiableMap(map); }
  • 11. Constant maps: After public static final ImmutableMap<String, Integer> ENGLISH_TO_INT = ImmutableMap .with(quot;fourquot;, 4) .with(quot;eightquot;, 8) .with(quot;fifteenquot;, 15) .with(quot;sixteenquot;, 16) .with(quot;twenty-threequot;, 23) .with(quot;forty-twoquot;, 42) .build();
  • 12. Defensive copies: Before private final Set<Integer> luckyNumbers; public Dharma(Set<Integer> numbers) { luckyNumbers = Collections.unmodifiableSet( new LinkedHashSet<Integer>(numbers)); } public Set<Integer> getLuckyNumbers() { return luckyNumbers; } Copy on the way in Wrap in unmodifiable on the way in or the way out
  • 13. Defensive copies: After private final ImmutableSet<Integer> luckyNumbers; public Dharma(Set<Integer> numbers) { luckyNumbers = ImmutableSet.copyOf(numbers); } public ImmutableSet<Integer> getLuckyNumbers() { return luckyNumbers; } Type, not just implementation What if you forget? Note: copyOf() cheats!
  • 14. Immutable Collections: more examples Sets: static final ImmutableSet<Country> BETA_COUNTRIES = ... ImmutableSet.of(); ImmutableSet.of(a); ImmutableSet.of(a, b, c); ImmutableSet.copyOf(someIterator); ImmutableSet.copyOf(someIterable); Small maps: static final ImmutableMap<Integer, String> MAP = ImmutableMap.of(1, quot;onequot;, 2, quot;twoquot;);
  • 15. Immutable Collections: caveats These collections are null-hostile In 95%+ of cases, this is what you want In other cases, fine workarounds exist This aligns with recent work on JDK collections (and it's a little faster this way) (and keeps the implementation simpler) Mutable elements can sometimes lead to confusion The resulting object won't be quot;deeply immutablequot;
  • 16. Immutable Collections: summary In the past, we'd ask, quot;does this need to be immutable?quot; Now we ask, quot;does it need to be mutable?quot;
  • 17. Overview 1. In a nutshell 2. Immutable Collections 3. Multisets 4. Multimaps 5. Other new types/impls 6. Static utilities 7. Other stuff 8. Q&A Questions also welcome throughout!
  • 18. Collection behavior When you have quot;a bunch of foosquot;, use a Collection -- but what kind? Can it have duplicates? Is ordering significant? (for equals()) Iteration order insertion-ordered? comparator-ordered? user-ordered? something else well-defined? or it just doesn't matter? In general, the first two determine the interface type, and the third tends to influence your choice of implementation.
  • 19. List vs. Set Set: unordered equality, no duplicates. List: ordered equality, can have duplicates. Ordered? Y N Dups? +------+-----+ Y | List | ? | +------+-----+ N | ? | Set | +------+-----+
  • 20. List vs. Set... and then some Multiset: unordered equality, can have duplicates. Ordered? Y N Dups? +------------+---------+ Y | List |Multiset!| +------------+---------+ N |(UniqueList)| Set | +------------+---------+ (UniqueList might appear in our library one day.)
  • 21. When to use a Multiset? quot;I kinda want a Set except I can have duplicatesquot; card game example changing to List sacrifices contains() performance quot;Are these Lists equal, ignoring order?quot; write a utility method for this? Histograms quot;What distinct tags am I using on my blog, and how many times do I use each one?quot; Multiset performance varies by the number of distinct elements, not total size.
  • 22. Multiset: tags example, before Map<String, Integer> tags = new HashMap<String, Integer>(); for (BlogPost post : getAllBlogPosts()) { for (String tag : post.getTags()) { int value = tags.containsKey(tag) ? tags.get(tag) : 0; tags.put(tag, value + 1); } } distinct tags: tags.keySet() count for quot;javaquot; tag: tags.containsKey(quot;javaquot;) ? tags.get (quot;javaquot;) : 0; total count: // oh crap...
  • 23. Multiset: tags example, after Multiset<String> tags = HashMultiset.create(); for (BlogPost post : getAllBlogPosts()) { tags.addAll(post.getTags()); } (... this space intentionally left blank ...) distinct tags: tags.elementSet(); count for quot;javaquot; tag: tags.count(quot;javaquot;); total count: tags.size();
  • 24. Multiset: tags example, after after What if you need to remove/decrement? Don't accidentally go negative Don't forget to prune! (Or just use a Multiset.) What about concurrency? Lock the entire map just to add one tag? (Or just use our ConcurrentMultiset.) When you use a powerful library, your code can easily evolve.
  • 25. Multiset API Everything from Collection, plus: int count(Object element); int add(E element, int occurrences); boolean remove(Object element, int occurrences); int setCount(E element, int newCount); boolean setCount(E e, int oldCount, int newCount);
  • 26. Multiset implementations ImmutableMultiset HashMultiset LinkedHashMultiset TreeMultiset EnumMultiset ConcurrentMultiset
  • 27. Overview 1. In a nutshell 2. Immutable Collections 3. Multisets 4. Multimaps 5. Other new types/impls 6. Static utilities 7. Other stuff 8. Q&A Questions also welcome throughout!
  • 28. Multimaps, before Ever done this? Map<Salesperson, List<Sale>> map = new HashMap<Salesperson, List<Sale>>(); public void makeSale(Salesperson salesPerson, Sale sale) { List<Sale> sales = map.get(salesPerson); if (sales == null) { sales = new ArrayList<Sale>(); map.put(salesPerson, sales); } sales.add(sale); }
  • 29. Multimaps, after Would you rather do this? Multimap<Salesperson, Sale> multimap = ArrayListMultimap.create(); public void makeSale(Salesperson salesPerson, Sale sale) { multimap.put(salesPerson, sale); } The code on the last slide is Verbose Bug-prone Limited in functionality Using the wrong abstraction
  • 30. About Multimaps A collection of key-value pairs (entries), like a Map, except that keys don't have to be unique. {a=1, a=2, b=3, c=4, c=5, c=6} multimap.get(key) returns a modifiable Collection view of the values associated with that key. Sometimes you want to think of it as a Map<K, Collection<V>> -- use the asMap() view: {a=[1, 2], b=[3], c=[4, 5, 6]}
  • 31. Multimap subtypes ListMultimap: the get() view implements List preserves the ordering of entries per key; can have duplicate entries SetMultimap: the get() view implements Set no duplicate entries, ordering of entries is impl- dependent SortedSetMultimap: the get() view implements SortedSet you get the idea Hmm... sounds a lot like a plain old Map<K, Collection<V>>? But wait...
  • 32. Multimap example 2, before Now we want to find the biggest Sale. Without Multimap: public Sale getBiggestSale() { Sale biggestSale = null; for (List<Sale> sales : map.values()) { Sale myBiggestSale = Collections.max(sales, SALE_CHARGE_COMPARATOR); if (biggestSale == null || myBiggestSale.getCharge() > biggestSale().getCharge()) { biggestSale = myBiggestSale; } } return biggestSale; }
  • 33. Multimap example 2, after With Multimap: public Sale getBiggestSale() { return Collections.max(multimap.values(), SALE_CHARGE_COMPARATOR); } View collections are very powerful. Multimap has six: get(), keys(), keySet(), values(), entries(), asMap().
  • 34. Multimap vs. Map Most Map methods are identical on Multimap: size(), isEmpty() containsKey(), containsValue() put(), putAll() clear() values() The others have analogues get() returns Collection<V> instead of V remove(K) becomes remove(K,V) and removeAll(K) keySet() becomes keys() (well, and keySet()) entrySet() becomes entries() And Multimap has a few new things containsEntry(), replaceValues()
  • 35. Multimap implementations ImmutableMultimap ArrayListMultimap HashMultimap LinkedHashMultimap TreeMultimap
  • 36. Overview 1. In a nutshell 2. Immutable Collections 3. Multisets 4. Multimaps 5. Other new types/impls 6. Static utilities 7. Other stuff 8. Q&A Questions also welcome throughout!
  • 37. BiMap aka unique-valued map, it guarantees its values are unique, as well as its keys Has an inverse() view, which is another BiMap bimap.inverse().inverse() == bimap Stop creating two separate forward and backward Maps! Let us do that for you. Implementations: ImmutableBiMap HashBiMap EnumBiMap
  • 38. ReferenceMap (If you haven't used weak or soft references, take a one- minute nap.) A generalization of java.util.WeakHashMap Nine possible combinations: strong, weak or soft keys strong, weak or soft values Fully concurrent implements ConcurrentMap cleanup happens in GC thread Isn't yet as fast as it could be, but we use it anyway
  • 39. Ordering class Comparator is easy to implement, but a pain to use. Ordering is Comparator++ (or RichComparator). Ordering<String> caseless = Ordering.forComparator( String.CASE_INSENSITIVE_ORDER); Now you have tasty methods like min(Iterable), max(Iterable), isIncreasing(Iterable), sortedCopy(Iterable), reverse()...
  • 40. Overview 1. In a nutshell 2. Immutable Collections 3. Multisets 4. Multimaps 5. Other new types/impls 6. Static utilities 7. Other stuff 8. Q&A Questions also welcome throughout!
  • 41. Static factory methods We has them. Rather than asking you to type Multimap<String, Class<? extends Handler>> handlers = new ArrayListMultimap<String, Class<? extends Handler>>(); you type Multimap<String, Class<? extends Handler>> handlers = ArrayListMultimap.create(); We provide these for JDK collections too, in classes called Lists, Sets and Maps. With overloads to accept Iterables to copy elements from
  • 42. Working with Itera*s Collection is a good abstraction when all your data is in memory Sometimes you want to process large amounts of data in a single pass Implementing Collection is possible but cumbersome, and won't behave nicely Iterator and Iterable are often all you need Our methods accept Iterator and Iterable whenever practical And ...
  • 43. quot;Iteratorsquot; and quot;Iterablesquot; classes These classes have parallel APIs, one for Iterator and the other for Iterable. Iterable transform(Iterable, Function)* Iterable filter(Iterable, Predicate)* T find(Iterable<T>, Predicate) Iterable concat(Iterable<Iterable>) Iterable cycle(Iterable) T getOnlyElement(Iterable<T>) Iterable<T> reverse(List<T>) These methods are LAZY! *No, this doesn't make Java into an FP language.
  • 44. Overview 1. In a nutshell 2. Immutable Collections 3. Multisets 4. Multimaps 5. Other new types/impls 6. Static utilities 7. Other stuff 8. Q&A Questions also welcome throughout!
  • 45. What we're not telling you about Forwarding collections Constrained collections Precondition checking Union/intersection/difference for Sets Multimaps.index() and Maps.uniqueIndex() ClassToInstanceMap ObjectArrays utilities AbstractIterator and PeekingIterator Join.join() and more
  • 46. How do we test this stuff? We have over 25,000 unit tests. How? return new SetTestSuiteBuilder() .named(quot;Sets.filterquot;) .withFeatures(GENERAL_PURPOSE, ALLOWS_NULL_VALUES, KNOWN_ORDER, CollectionSize.ANY) .using(new TestStringCollectionGenerator() { public Set<String> create(String[] elements) { return Sets.filter(...); } }) .createTestSuite(); Googlers George van den Driessche and Chris Povirk We'll open-source this framework too Several JDK collections don't pass all its tests!