SlideShare a Scribd company logo
1 of 154
Download to read offline
Google
Guava

       &

Eclipse
Modeling
Framework
2011/04/26   Mikaël Barbero
Introduction



http://www.flickr.com/photos/drspam/295023450/
                                                          1
About me
‣ Modeling consultant
‣ Research engineer
‣ Trainer
‣ Conference Speaker
‣ Language guy ;)

   ‣ Eclipse committer
   ‣ Guava-OSGi packager
   ‣ EMFPath lead
Paris

        Nantes
Strategic
members
Acceleo
EMFCompare
ATL
GMF
OCL
Mylyn Intent
EEF            Leading
STP
Ava ilable technologies
Guava
                                                   Overview



http://www.flickr.com/photos/slowburn/2986303105/
                                                              2
http://www.flickr.com/photos/awagnon/1626025855/
About Guava


Java library used   Superset of
  internally @        Google
Google for years    Collections
About Guava




   Apache License v2
http://www.apache.org/licenses/LICENSE-2.0
About Guava

                            s                                               s
                       ti on                                          ti on
                      c
                  lle                                           llec
                Co 5                                          Co                     a r03          a r08
             gle v0.                                       gle v1                 uav            uav
       G   oo                                          G oo                     G              G

2007                      2008             2009                     2010                     2011




                   Frequent releases (quarterly base)
                                 Latest release (r09): April, 7th
Why using Guava?


Simp lexity




                       http://www.flickr.com/photos/gio_vencato/4941064345/
Why using Guava?




         http://www.flickr.com/photos/reway2007/3300379295/
Why using Guava?

Mainstream?




                  http://www.flickr.com/photos/funtik/1175522045/
Why using Guava?




Helping
others
                   http://www.flickr.com/photos/thearches/4381959041/
Inside Guava

IO                  Networking                  Concurrency




     Primitive types               Collections



     GWT compatibility is tested (see @GwtCompatible)
Comparison with
                      Apache Commons
                         Better                                                   Better
More Modern
                        Designed                                                Supported

                 Best practices                                                  Actively
   Java 5                                                                       developed
                  and patterns                                                       (- commons 3.0)




Respects JDK                                                                   Google
               Orthogonality
  contracts           (@Beta to test designs)                               depends on it
                                                                                   (e.g., Google Guice)

               http://stackoverflow.com/questions/4542550/what-are-the-big-improvements-between-guava-and-apache-equivalent-libraries
B est
 rep.
Corest of the
                                                           core



http://www.flickr.com/photos/27384147@N02/5211738745/
                                                                  3
Objects class
public class Person {
	 final String name, nickname;
	 final Movie favMovie;

	   @Override
	   public boolean equals(Object object) {
	   	 if (object instanceof Person) {
	   	 	 Person that = (Person) object;
	   	 	 return Objects.equal(this.name, that.name)
	   	 	 	 	 && Objects.equal(this.nickname, that.nickname)
	   	 	 	 	 && Objects.equal(this.favMovie, that.favMovie);
	   	 }
	   	 return false;
	   }

	   @Override
	   public int hashCode() {
	   	 return Objects.hashCode(name, nickname, favMovie);
	   }
}

                 Example from http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Objects class
public class Person {
	 final String name, nickname;
	 final Movie favMovie;
  //...
	
  @Override
	 public String toString() {
	 	 return Objects.toStringHelper(this)
	 	 	 	 .add("name", name)
	 	 	 	 .add("nickname", nickname)
	 	 	 	 .add("favMovie", favMovie)
	 	 	 	 .toString();
	 }

	 public String preferredName() {
	 	 return Objects.firstNonNull(nickname, name);
	 }
}

        Example from http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Preconditions
Defensive coding

       if (state != State.PLAYABLE) {
       	 throw new IllegalStateException(
       	 	 "Can't play movie; state is " + state);
       }




     Preconditions.checkState(state == State.PLAYABLE,
     	 	 "Can't play movie; state is %s", state);




              Example from http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Preconditions
Defensive coding

        public void setRating(StarRating rating) {
        	 if (rating == null) {
        	 	 throw new NullPointerException();
        	 }
        	 this.rating = rating;
        }



        public void setRating(StarRating rating) {
        	 this.rating = checkNotNull(rating);
        }



             Example from http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Equivalences strategies
public interface Equivalence<T> {
  boolean equivalent(@Nullable T a, @Nullable T b);
  int hash(@Nullable T t);
}




 Equivalence equals = Equivalences.equals();
 Equivalence identity = Equivalences.identity();




  Equivalence<String> elementEquivalence = ...;
  Equivalence<Iterable<String>> pairwise =
  	 Equivalences.pairwise(elementEquivalence);
  Collection<String> c1, c2;
  pairwise.equivalent(c1, c2);
Suppliers
                public interface Supplier<T> {
                  T get();
                }




Supplier<String> s = ...;
	
Supplier<String> memoizing = Suppliers.memoize(s);
	
Supplier<String> expiring =
	 	 Suppliers.memoizeWithExpiration(s, 100, TimeUnit.SECONDS);
	
Supplier<String> ofInstance =
	 	 Suppliers.ofInstance("Always returning");
Throwables
Throwables.getCausalChain(throwable);
Throwables.getRootCause(throwable);

Throwables.getStackTraceAsString(throwable);

Throwables.propagateIfInstanceOf(throwable, IOException.class);

Throwables.propagateIfPossible(throwable);

try {
	 someMethodThatCouldThrowAnything();
} catch (IKnowWhatToDoWithThisException e) {
	 handle(e);
} catch (Throwable t) {
	 Throwables.propagateIfPossible(t);
	 throw new RuntimeException("unexpected", t);
}
@Annotation


    @Beta        @VisibleForTesting




@GwtCompatible   @GwtIncompatible
Strings



http://www.flickr.com/photos/gernot/2554175292/
                                                           4
CharMatcher                     +1

        StringUtil example:
        allAscii, collapse, collapseControlChars, collapseWhitespace, indexOfChars, lastIndexNotOf,
        numSharedChars, removeChars, removeCrLf, replaceChars, retainAllChars, strip,
        stripAndCollapse, stripNonDigits, ...



                        Partial cross product of two notions:
                         (a) what's a "matching" character?
                   (b) what to do with those matching characters?

        CharMatcher:
        An instance of this type represents part (a),
        and the operation you invoke on it represents part (b).

http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Getting a CharMatcher
      CharMatcher.WHITESPACE (Unicode)
      CharMatcher.JAVA_DIGIT
                               Predefined constants
      CharMatcher.ASCII
                                   (examples)
      CharMatcher.ANY

                                                                   Factory methods
                            CharMatcher.is('x')                       (examples)
                            CharMatcher.isNot('_')
                            CharMatcher.oneOf("aeiou").negate()
                            CharMatcher.inRange('a', 'z').or(inRange('A', 'Z'))
                          Subclass CharMatcher, implement matches(char c)
                                    Now check out all that you can do...
http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Using your CharMatcher
                     ‣ boolean matchesAllOf(CharSequence)
                     ‣ boolean matchesAnyOf(CharSequence)
                     ‣ boolean matchesNoneOf(CharSequence)
                     ‣ int indexIn(CharSequence, int)
                     ‣ int lastIndexIn(CharSequence, int)
                     ‣ int countIn(CharSequence)
                     ‣ String removeFrom(CharSequence)
                     ‣ String retainFrom(CharSequence)
                     ‣ String trimFrom(CharSequence)
                     ‣ String trimLeadingFrom(CharSequence)
                     ‣ String trimTrailingFrom(CharSequence)
                     ‣ String collapseFrom(CharSequence, char)
                     ‣ String trimAndCollapseFrom(CharSequence, char)
                     ‣ String replaceFrom(CharSequence, char)
http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Using your CharMatcher
                    String string = "Scream 4";
                    CharMatcher matcher = CharMatcher.JAVA_LETTER_OR_DIGIT;
                    int count = matcher.countIn(string);

                    System.out.println("Letter or digit count: "+count);
                    // Letter or digit count: 7

                    System.out.println(matcher.matchesAllOf("scream"));
                    // true

                    System.out.println(matcher.matchesAllOf("scream "));
                    // false

                    System.out.println(matcher.matchesNoneOf("_?=)("));
                    // true



http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-1.html
Splitter                                +1
      JDK has splitter
                  ‣ regular expression
                  ‣ result as an array
                  ‣ its way of handling empty pieces                             (which is very strange)



                                    Mini-puzzler
                                                    ",a,,b,".split(",") returns...
                                                    (a) "", "a", "", "b", ""
                                                    (b) null, "a", null, "b", null
                                                    (c) "a", null, "b"
                                                    (d) "a", "b"
                                                    (e) None of the above
http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Splitter




                                                                               e_s_jones/5060802981/
                                            http://www.flickr.com/photos/terenc




                         Splitter is String.split() on steroids
http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Splitter
              The default behavior is simplistic:
              //yields [" foo", " ", "bar", " quux", ""]
              Splitter.on(',').split(" foo, ,bar, quux,");




              If you want extra features, ask for them!
              //yields ["foo", "bar", "quux"]
              Splitter.on(',')
              	 .trimResults()
              	 .omitEmptyStrings()
              	 .split(" foo, ,bar, quux,");



http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Ascii, Charsets
Ascii
  list of bytes constants for each
  Char between 0x00 & 0x7F
Charsets

                                 by
 G   uaranteed to be supported
                                 ons
 al l Java platform implementati
                                                      No more
  ‣Charsets.ISO_8859_1;                try {
                                       	 bytes = string.getBytes("UTF-8");
  ‣Charsets.US_ASCII;                  } catch (UnsupportedEncodingException e) {
  ‣Charsets.UTF_16;                    	 // how can this possibly happen?
  ‣Charsets.UTF_16BE;                  	 throw new AssertionError(e);
                                       }
  ‣Charsets.UTF_16LE;
  ‣Charsets.UTF_8;
Strings

String str = Strings.emptyToNull(s);



String str = Strings.nullToEmpty(s);



boolean b = Strings.isNullOrEmpty(s);
CaseFormat
     ‣ LOWER_CAMEL
      ‣ Java variable naming convention, e.g., "lowerCamel".

     ‣ LOWER_HYPHEN
      ‣ Hyphenated variable naming convention, e.g., "lower-hyphen".

     ‣ LOWER_UNDERSCORE
      ‣ C++ variable naming convention, e.g., "lower_underscore".

     ‣ UPPER_CAMEL
      ‣ Java and C++ class naming convention, e.g., "UpperCamel".

     ‣ UPPER_UNDERSCORE
      ‣ Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE".


E xample    CaseFormat.to(CaseFormat.UPPER_UNDERSCORE, s);
Collections



http://www.flickr.com/photos/tochis/1169807846/
                                                           5
Ordering

                                               {
                                Co mparator<T>
              publ ic interface             );
                           int compare(T, T
              	 abstract            equals(Objec
                                                 t);
                               ean
              	 a bstract bool
               }




         Comparator is easy to implement, but a pain to use

         Push the Comparator<T> interface to the next level


http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
Ordering                                                  public class Employee implements Comparable<Employee> {
                                                                         	   private final int id;
                                                                         	   private final String name;
                                                                         	   private final int yearsOfService;

                                                                         	     public Employee(int id, String name, int yearsOfService) {
                                                                         	     	   this.id = id;
                                                                         	     	   this.name = name;
                                                                         	     	   this.yearsOfService = yearsOfService;
                                                                         	     }



                    Simple
                                                                         	     public int getId() { return id; }

                                                                         	     public String getName() { return name; }


                   data class                                            	     public int getYearsOfService() { return yearsOfService; }

                                                                         	     @Override
                                                                         	     public int compareTo(Employee employee) {
                                                                         	     	   return this.getName().compareTo(employee.getName());
                                                                         	     }

                                                                         	     @Override
                                                                         	     public String toString() {
                                                                         	     	   return Objects.toStringHelper(this)
                                                                         	     	   	    .add("id", id)
                                                                         	     	   	    .add("name", name)
                                                                         	     	   	    .add("years of service", yearsOfService)
                                                                         	     	   	    .toString();
                                                                         	     }
                                                                         }


http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
Ordering

     Employee anakinSk = new Employee(4, "Anakin Skywalker", 4);
     Employee darthVader = new Employee(3, "Darth Vader", 5);
     Employee hanSolo = new Employee(2, "Han Solo", 10);
     List <Employee> employeeList =
        Lists.newArrayList(anakinSk, hanSolo, darthVader);
     System.out.println("employee list: "+employeeList);




                                                employee list: [Employee{id=4, name=Anakin
                                                Skywalker, years of service=4}, Employee{id=2,
                                                name=Han Solo, years of service=10}, Employee
                                                {id=3, name=Darth Vader, years of service=5}]




http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
Ordering
     Define your own Comparator
   Comparator<Employee> yearsComparator = new Comparator<Employee>() {
   	 @Override
   	 public int compare(Employee employee1, Employee employee2) {
   	 	 return (employee1.getYearsOfService() - employee2
   	 	 	 	 .getYearsOfService());
   	 }
   };



       Comparator<Employee> idComparator = new Comparator<Employee>() {
       	 @Override
       	 public int compare(Employee employee1, Employee employee2) {
       	 	 return (employee1.getId() - employee2.getId());
       	 }
       };

http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
Ordering
        Create an Ordering from a Comparator
                               Ordering<Employee> orderUsingYearsComparator =
                               	 Ordering.from(yearsComparator);



         Use your ordering, e.g. to sort
                     List<Employee> sortedCopy =
                     	 orderUsingYearsComparator.sortedCopy(employeeList);
                     System.out.println("sorted copy: " + sortedCopy);


                      sorted copy: [Employee{id=4, name=Anakin Skywalker,
                      years of service=4}, Employee{id=3, name=Darth Vader,
                      years of service=5}, Employee{id=2, name=Han Solo,
                      years of service=10}]

http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
Ordering
       toString() ordering

            Ordering<Object> toStringOrdering = Ordering.usingToString();




        Natural ordering (Comparable<T>)

                             Ordering<Employee> natural = Ordering.natural();




http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
What you can do with Ordering

‣ Ordering.min(Iterable<E>)
‣ Ordering.max(Iterable<E>)
‣ Ordering.leastOf(Iterable<E>, int)
‣ Ordering.greatestOf(Iterable<E>, int)
‣ Ordering.isOrdered(Iterable<? extends T>)
‣ Ordering.isStrictlyOrdered(Iterable<? extends T>)
‣ Ordering.binarySearch(List<? extends T>, T)
What you can do with Ordering

‣ Ordering.sortedCopy(Iterable<E>)
‣ Ordering.immutableSortedCopy(Iterable<E>)


            new TreeSet( Collection)
Better than
                 card duplicate s elements
       Do not dis
                     Performed    sort is stable
Ordering is configurable
         ‣ Ordering.reverse()
         ‣ Ordering.lexicographical()
         ‣ Ordering.nullsFirst()
         ‣ Ordering.nullsLast()
         ‣ Ordering.reverse()

Lexicographical returns an
Ordering on Iterable of T
                       [] < [1] < [1, 1] < [1, 2] < [2]
ObjectArrays

‣ concat(T, T[])
‣ concat(T[], T)
‣ concat(T[], T[], Class<T>)
‣ newArray(Class<T>, int)
‣ newArray(T[], int)
Multiset & Multimap
Historically, multisets (aka bags) and
  multimaps emulated atop maps



   Multimap = Map<K, List<V>>




    Multiset = Map<K, Integer>
When to use Multiset?
      ‣"I kinda want a Set except I can have duplicates"
        ‣ card games example
             ‣ changing to List sacrifices contains() performance
      ‣"Are these Lists equal, ignoring order?"
             ‣ write a utility method for this? Histograms
      ‣"What distinct tags am I using on my blog, and how
      many times do I use each one?"


                       Multiset performance varies by the number
                           of distinct elements, not total size.

http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Multiset
    Ever done this?
           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 "java" tag:
                   Usage                                                     tags.containsKey("java") ? tags.get("java") : 0;
                                                                   total count:
                                                                             // oh crap...

http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Multiset
  Would you rather do this?
                              Multiset<String> tags = HashMultiset.create();
                              for (BlogPost post : getAllBlogPosts()) {
                                tags.addAll(post.getTags());
                              }




                                                                                         distinct tags:
                                                                                           tags.elementSet();

                                   Usage                                                 count for "java" tag:
                                                                                           tags.count("java");
                                       (hurrah)
                                                                                         total count:
                                                                                           tags.size();



http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Multiset API
        ‣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.

http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Multiset API

       ‣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);

http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Multiset implementations                                  +1



                                                     ImmutableMultiset
                                                     HashMultiset
                                                     LinkedHashMultiset
                                                     TreeMultiset
                                                     EnumMultiset
                                                     ConcurrentHashMultiset




http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
When to use Multimap?

        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);
              }




http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
When to use Multimap?
  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 previous slide is
                                       ‣Verbose
                                       ‣Bug-prone
                                       ‣Limited in functionality
                                       ‣Using the wrong abstraction
http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
More about Multimap
          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]}
http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
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...
http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Multimap, 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;
}

http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Multimap, after
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().
http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Multimap API
                   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()
http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Multimap implementations                                                +1


                                                         ImmutableMultimap
                                                       ImmutableListMultimap
                                                       ImmutableSetMultimap
                                                          ArrayListMultimap
                                                            HashMultimap
                                                        LinkedHashMultimap
                                                         LinkedListMultimap
                                                            TreeMultimap
                                                                                            ListMultimap
                                                                                            SetMultimap
                                                                                         SortedSetMultimap

http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
BiMap       +1


            aka unique-valued map
             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!

http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
BiMap Implementations


                                                             ImmutableBiMap
                                                             HashBiMap
                                                             EnumBiMap
                                                             EnumHashBiMap




http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Constrained Collections/Maps

public interface Constraint<E> {
	 E checkElement(E element);
}




                //...
                public Object checkElement(Object element) {
                	 if (element == null) {
                	 	 throw new NullPointerException();
                	 }
                	 return element;
                }                          Constraints.n
                                                         otNull()
                //...
Constrained Collections/Maps

Constraints.
  constrainedCollection(Collection<E>, Constraint<? super E>)

  constrainedList(List<E>, Constraint<? super E>)

  constrainedMultiset(Multiset<E>, Constraint<? super E>)

  constrainedSet(Set<E>, Constraint<? super E>)

  constrainedSortedSet(SortedSet<E>, Constraint<? super E>)
MapMaker                       +1


A ConcurrentMap builder, providing any combination of
these features:
  ‣Soft or weak keys
  ‣Soft or weak values
  ‣Timed expiration
  ‣On-demand computation of values
Far more powerful, easy to use than WeakHashMap

Concurrent on-demand computation is really hard
MapMaker

ConcurrentMap<User, Graph> recommendations =
	 	 	 new MapMaker()
          .concurrencyLevel(4)
	 	 	 	 .softKeys()
          .weakValues()
          .maximumSize(10000)
	 	 	 	 .expireAfterWrite(10, TimeUnit.MINUTES)
	 	 	 	 .makeComputingMap(
	 	 	 	 	 new Function<User, Graph>() {
	 	 	 	 	 	 public Graph apply(User user) {
	 	 	 	 	 	 	 return createExpensiveGraph(user);
	 	 	 	 	 	 }
	 	 	 	 	 });
Forwarding Object/Collections

 Abstract implementations of existing types
 delegating all method calls to its delegate()


       protected abstract Object delegate();




  Decorator pattern without the burden ;)
Forwarding Collections

  ForwardingCollection     ForwardingMultiset
ForwardingConcurrentMap     ForwardingObject
    ForwardingIterator      ForwardingQueue
      ForwardingList          ForwardingSet
  ForwardingListIterator ForwardingSetMultimap
 ForwardingListMultimap   ForwardingSortedMap
      ForwardingMap       ForwardingSortedSet
   ForwardingMapEntry ForwardingSortedSetMultimap
   ForwardingMultimap        ForwardingTable
Static utilities
In classes with name ending with an s

                    ‣ Lists
                    ‣ Maps
                    ‣ Multimaps
                    ‣ Multisets
                    ‣ Sets
                    ‣ SortedMaps
                    ‣ Tables
                    ‣ Iterators
                    ‣ Iterables
                    ‣ Collections2
Static factories methods                        +1
Rather than typing
     Map<String, Class<? extends Handler>> m =
     	 new HashMap<String, Class<? extends Handler>>();



you type
 Map<String, Class<? extends Handler>> m2 = Maps.newHashMap();



           Guava provides these for JDK collections
             and for Guava collections (Multi*...)

            With overloads to accept Iterables to
                    copy elements from
Maps as index                            +1

Maps.uniqueIndex()


     Map<Integer, Employee> m = Maps.uniqueIndex(values,
     	 new Function<Employee, Integer>() {
     	 	 @Override
     	 	 public Integer apply(Employee input) {
     	 	 	 return input.getId();
     	 	 }
     });
Multimaps as index                              +1

Multimaps.index()

    Multimap<Integer, Employee> m = Multimaps.index(values,
    	 new Function<Employee, Integer>() {
    	 	 @Override
    	 	 public Integer apply(Employee input) {
    	 	 	 return input.getYearsOfService();
    	 	 }
    });
Map differences                     +1

        So you want to compute the differences
                 between two maps


   Guava has it too
              Maps.difference(
              	 Map<? extends K,? extends V>,
              	 Map<? extends K,? extends V>)




Difference is an immutable snapshot of the state of the
        maps at the time this method is called
MapDifference API

          Map<K,V> entriesInCommon()
          Map<K,V> entriesOnlyOnLeft()
          Map<K,V> entriesOnlyOnRight()


Map<K,MapDifference.ValueDifference<V>> entriesDiffering()

                   ValueDifference API

                      V leftValue()
                      V rightValue()
Sets union/intersection/difference
                                                  +1
difference(Set<E>, Set<?>)

symmetricDifference(Set<? extends E>, Set<? extends E>)

union(Set<? extends E>, Set<? extends E>)

intersection(Set<E>, Set<?>)


                Returns Sets.SetView<E>
Sets combinations
Set<Set<E>> powerSet(Set<E>)

    while the power set of a set with size n is of size 2^n,
               its memory usage is only O(n)

Set<List<B>> cartesianProduct(
        List<? extends Set<? extends B>>)

      while the cartesian product of sets of size m, n, p
        is a set of size m x n x p, its actual memory
         consumption is much smaller (m + n + p)
Immutable collections

     JDK has Collections.unmodifiableFoo wrappers

          ‣Unmodifiable - you can't change it
          ‣Immutable - it can never change, no matter what
          ‣Immutability is tasty!
               ‣See Effective Java Item 15 for some of the many reasons


http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Immutable collections                             +1


                                                              ImmutableList
                                                              ImmutableSet
                                                             ImmutableMap
                                                        ImmutableSortedMap
                                                         ImmutableSortedSet
                                                           ImmutableMultiset
                                                          ImmutableMultimap
                                                       ImmutableListMultimap
                                                       ImmutableSetMultimap
                                                            ImmutableBiMap
http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Immutable collections
       JDK wrappers still useful for unmodifiable views of
       changing data. But for most purposes, use Guava’s:

       ‣Brand-new, standalone implementations
       ‣Immutability guaranteed!
       ‣Very easy to use
            ‣See following slides
       ‣Slightly faster
       ‣Null hostile
       ‣Use less memory
            ‣Sometimes far less (ImmutableSet, factor of 2-3x)
http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
Immutable collections
Factory methods
    ImmutableXXX.of() immutable empty XXX
    ImmutableXXX.of(E) singletons
    ImmutableXXX.of(E, E)
    ImmutableXXX.of(E, E, E, E...)

    ImmutableXXX.copyOf(Iterable)
    ImmutableXXX.copyOf(Iterator)
                                            small maps only (up
    ImmutableMap.of(1, "one", 2, "two")     to 5 key/value pairs)
    ImmutableMap.copyOf(Map)
Builder pattern otherwise
Constants Sets


                     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);
                     	 }




http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Constants Sets

                    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.


http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Constants Sets
                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


http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Constants Maps

     public static final Map<String, Integer> ENGLISH_TO_INT;
     static {
     	 Map<String, Integer> map = new LinkedHashMap<String, Integer>();
     	 map.put("four", 4);
     	 map.put("eight", 8);
     	 map.put("fifteen", 15);
     	 map.put("sixteen", 16);
     	 map.put("twenty-three", 23);
     	 map.put("forty-two", 42);
     	 ENGLISH_TO_INT = Collections.unmodifiableMap(map);
     }




http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Constants Maps

                   public static final ImmutableMap<String, Integer>
                   ENGLISH_TO_INT =
                   	 	 	 ImmutableMap.<String,Integer>builder()
                   	 	 	 .put("four", 4)
                   	 	 	 .put("eight", 8)
                   	 	 	 .put("fifteen", 15)
                   	 	 	 .put("sixteen", 16)
                                                                   Empowering the
                   	 	 	 .put("twenty-three", 23)                  Builder Pattern!
                   	 	 	 .put("forty-two", 42)
                   	 	 	 .build();




http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Table                     @Beta
                                                       since r07
Collection with columns and rows
No more Map<T1, Map<T2,T3>>
Table<R,C,V> composed of Table.Cell<R,C,V>
Tables.transpose() (flips row and column keys)

                  6 views                          2 impl.
    Set<Table.Cell<R,C,V>> cellSet()
         Map<R,V> column(C)                     HashBasedTable
        Set<C> columnKeySet()                   TreeBasedTable
    Map<C,Map<R,V>> columnMap()
           Map<C,V> row(R)
          Set<R> rowKeySet()
     Map<R,Map<C,V>> rowMap()
http://www.flickr.com/photos/leamarzloff/3085027173/




                                                      Functionnal
                                                         flavor


                                                                6
in com.google.common.base package


                                    public interface Predicate<T> {
 Predicate<T> to filter                boolean apply(T from);
    out a collection                }




                                {
public interface Function<F, T>
  T apply(F from);
                                          Function<F, T> to
}                                       transform a collection
in com.google.common.collect package




                                                                           Iterables.filter()
                                                                          Iterators.filter()
                                                                         Collections2.filter()
                                                                             Sets.filter()



http://www.flickr.com/photos/luis_is_rubbish_at_photography/5464233571/
24           42           13           7           128


public static void demo(Collection<Integer> c) {
	 	 Predicate<Integer> isEven = new Predicate<Integer>() {
	 	 	 @Override
	 	 	 public boolean apply(Integer input) {
	 	 	 	 return (input.intValue() % 2 == 0);
	 	 	 }
	 	 };
	 	 Collection<Integer> fCol =
       Collections2.filter(c, isEven);
	 }




               24           42          128
in com.google.common.collect package




 Iterables.transform()
 Iterators.transform()
Collections2.transform()
   Lists.transform()

                           http://www.flickr.com/photos/brotherxii/2203037632
                                                                             /
Apple         Orange          Banana           Kiwi            Pear



public void demo(Collection<String> c) {
	 	 Function<String, String> toUpperCase = new Function<String, String>() {
	 	 	 @Override
	 	 	 public String apply(String input) {
	 	 	 	 return input.toUpperCase();
	 	 	 }
	 	 };
	 	 Collection<String> tCol = Collections2.transform(c, toUpperCase);
	 }




   APPLE        ORANGE         BANANA             KIWI           PEAR
Beware
of


lazyness   http://www.flickr.com/photos/torek/2467519466/
Copy!
                                                         Lists.newArrayList()
                                                         Lists.newLinkedList()
                                                         Sets.newHashSet()
                                                         Sets.newLinkedHashSet()
                                                         Sets.newTreeSet()



                                                          or make it immutable...

                                                                 ImmutableList.copyOf()
                                                                 ImmutableSet.copyOf()
http://www.flickr.com/photos/visionnewspaper/314107094/
Compose and combine
                      http://www.flickr.com/photos/jgscism/5484243543/




Functions
    compose
    forPredicate

Predicates
     and
     or
     not
     compose
Compose and combine
    Function<String, String> toUpper = new Function<String, String>() {
    	 @Override
    	 public String apply(String input) {
    	 	 return input.toUpperCase();
    	 }
    };




 Function<Integer, String> toHexString = new Function<Integer, String>() {
 	 @Override
 	 public String apply(Integer input) {
 	 	 return Integer.toHexString(input.intValue());
 	 }
 };




        Function<Integer, String> toUpperHexString =
            Functions.compose(toUpper, toHexString);
Compose and combine
 Predicate<String> isEmpty = new Predicate<String>() {
 	 @Override
 	 public boolean apply(String input) {
 	 	 return input.length() == 0; // isEmpty() is Java6 only
 	 }
 };


     Predicate<Object> isNull = new Predicate<Object>() {
     	 @Override
     	 public boolean apply(Object input) {
     	 	 return input == null;
     	 }
     };


Predicate<String> nullOfEmpty = Predicates.or(isNull, isEmpty);
Maps transform & filter
Maps.filterEntries()

Maps.filterKeys()

Maps.filterValues()

Maps.transformEntries()

Maps.transformValues()

          Equivalence for Multimaps
Primitives



             7
common.primitives

          package that helps you work with the primitive types
                                                          int, long, double, float, char, byte, short, and boolean




               If you need help doing a primitive task:

                    1. check the wrapper class (e.g. java.lang.Integer)
                    2. check java.util.Arrays
                    3. check com.google.common.primitives
                    4. it might not exist!

http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
common.primitives
       Contains the classes
        Booleans,
                                                                    Each has the exact same structure
        Bytes,                                                      (but has only the subset of operations that make sense for its type).

        Chars,
        Doubles,
        Floats,                                                     Many of the byte-related methods
        Ints,                                                      have alternate versions in the classes
        Longs and (wait for it)                                      SignedBytes and UnsignedBytes.
                                                                                           (Bytes are peculiar...)
        Shorts



                             Guava doesn't do primitive-based collections; try fastutil, or trove4j, or...
http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
The big table
         Method                   Longs              Ints          Shorts   Chars Doubles   Bytes   S.Bytes U.Bytes Booleans
       hashCode                       x                x             x       x       x       x                         x
        compare                       x                x             x       x       x                x       x        x
    checkedCast                                        x             x       x                        x       x
     saturadCast                                       x             x       x                        x       x
        contains                      x                x             x       x       x       x
        indexOf                       x                x             x       x       x       x                         x
     lastIndexOf                      x                x             x       x       x       x                         x
            min                       x                x             x       x                        x       x
            max                       x                x             x       x                        x       x
          concat                      x                x             x       x       x       x                         x
            join                      x                x             x       x                        x       x        x
         toArray                      x                x             x       x       x       x                         x
           asList                     x                x             x       x       x       x                         x
  lexComparator                       x                x             x       x                        x       x        x
     toByteArray                      x                x             x       x
  fromByteArray                       x                x             x       x
http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
http://www.flickr.com/photos/buzzingbye/222969493/




                                                    IO & Network



                                                              8
common.io                                                           2 key interfaces
                                                                   public interface InputSupplier<T> {
                                                                   	 T getInput() throws IOException;
                                                                   }
           Typically:
                                                                   public interface OutputSupplier<T> {
           InputSupplier<InputStream>,
           OutputSupplier<Writer>, etc.                            	 T getOutput() throws IOException;
                                                                   }




             This lets all Guava’s utilities be useful for many kinds of I/O.

      Terminology
                     ‣ byte stream means "InputStream or OutputStream"
                               ByteStreams utilities class
                     ‣ char stream means "Reader or Writer."
                               CharStreams utilities class

http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
ByteStreams
           ‣byte[] toByteArray(InputStream)
           ‣byte[] toByteArray(InputSupplier)
           ‣void readFully(InputStream, byte[])
           ‣void write(byte[], OutputSupplier)
           ‣long copy(InputStream, OutputStream)
           ‣long copy(InputSupplier, OutputSupplier)
           ‣long length(InputSupplier)
           ‣boolean equal(InputSupplier, InputSupplier)
           ‣InputSupplier slice(InputSupplier, long, long)
           ‣InputSupplier join(InputSupplier...)
                                      CharStreams is similar, but deals in Reader, Writer, String and
                                       CharSequence (often requiring you to specify a Charset).

http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Files                                           The Files class works one level higher than
                                                                  ByteStreams and CharStreams


         byte[] toByteArray(File)
         void write(byte[], File)
         void write(CharSequence, File, Charset)
         long copy(File, File)
         long copy(InputSupplier, File)
         long copy(File, OutputSupplier)
         long copy(File, Charset, Appendable)
         long move(File, File)
         boolean equal(File, File)

http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
More about Files

                    File createTempDir()
                    void deleteDirectoryContents(File)
                    void deleteRecursively(File)
                    long getChecksum(File, Checksum)
                    byte[] getDigest(File, MessageDigest)
                    String readFirstLine(File, Charset)
                    List<String> readLines(File, Charset)
                    T readLines(File, Charset, LineProcessor<T>)
                    String toString(File, Charset)

http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Flushab les and Closeables
      Flushables.flushQuietly(Flushable flushable)
      Flushables.flush(
        Flushable flushable,
        boolean swallowIOException) throws IOException



     Closeables.closeQuietly(Closeable closeable)
     Closeables.close(
       Closeable closeable,
       boolean swallowIOException) throws IOException



                                                  Very usefull in finally blocks
                                                   (avoid nesting try/catch)

http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
common.net
                                                                                   ‣URI
                                              Work with literals of:               ‣URL
                                                                                   ‣@IP (v4/v6)
                                    Never cause DNS services to
                                            be accessed
                                                                   (JDK does...)




       HostSpecifier
                 syntactically valid host specifier, suitable for use in a URI
       InternetDomainName
                 ~RFC 1035, i18n DN
       InetAddresses
                 utility pertaining to Inet(4|6)Address instances

http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Concurrency



http://www.flickr.com/photos/kh-67/3339157498/
                                                          9
Concurrency in Guava


                                                   Immutable*
                                            ConcurrentHashMultiset
                                         Multimaps.synchronizedMultimap
                                                    MapMaker




http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
comm on.util.concurrent
                     It’s all about Future (as in java.util.concurrent)
                                                                 (never heard of it, go take a nap)




                           "A handle to an in-progress computation."

        "A promise from a service to supply us with a result."



http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
Future
                                     JDK Future
                 public interface Future<V> {
                 	 	 //...
                 	 	 V get();
                 	 	 //...
                 	 }




                                                                         Guava ListenableFuture
                       public interface ListenableFuture<V> extends Future<V> {
                       	 	 void addListener(Runnable r, Executor e);
                       	 }



http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
ListenableFuture

                           Future with one new method: addListener

                      When the future is done (success, exception,
                            cancellation), the listeners run

             the killer app: "To serve as a foundation for higher-
                               level abstractions"

                                                                         See Futures

http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
ListenableFuture
      When to use? Always.

      (+) Most Futures methods require it.
      (+) It's easier than changing to ListenableFuture later.
      (+) Providers of utility methods won't need to provide
      Future and ListenableFuture variants of their methods.

      (−) "ListenableFuture" is lengthier than "Future."
      (−) Classes like ExecutorService give you a plain
      Future by default.

http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
Transform and chain

                 Function<QueryResult, List<Row>> rowsFunction =
                   new Function<QueryResult, List<Row>>() {
                   	 public List<Row> apply(QueryResult queryResult) {
                   	 	 return queryResult.getRows();
                   	 }
                   };

                 Future<QueryResult> queryFuture = ...;
                 Future<List<Row>> rowsFuture = transform(queryFuture,
                 rowsFunction);




http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
Transform and chain

   Function<RowKey, ListenableFuture<QueryResult>> queryFunction =
     new Function<RowKey, ListenableFuture<QueryResult>>() {
     	 public ListenableFuture<QueryResult> apply(RowKey rowKey) {
     	 	 return dataService.read(rowKey);
     	 }
     };

   ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
   ListenableFuture<QueryResult> queryFuture = chain(rowKeyFuture,
   queryFunction);




http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
Futures

     Got a Iterable<Future<V>>?


     Decide what you want:

            Future of List<V>                                            Futures.allAsList()
            List of Future<V>                                            Futures.successfulAsList()



http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
Executors

                     MoreExecutors.sameThreadExecutor
                               for quick tasks that can run inline
                     MoreExecutors.getExitingExecutorService
                               for "half-daemon" threads
                     UncaughtExceptionHandlers.systemExit
                               for exiting after unexpected errors
                     ThreadFactoryBuilder
                               new ThreadFactoryBuilder()
                                 .setDaemon(true)
                                 .setNameFormat("WebRequestHandler-%d")
                                 .build();

http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
Services



                   "An object with an operational state, plus
               asynchronous start() and stop() lifecycle methods
                     to transfer into and out of this state."
                                     Example: web servers, RPC servers, monitoring initialization, ...




http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
Services

    AbstractExecutionThreadService
              One thread automatically created for you at startup

    AbstractIdleService
              Thread only needed for startup and shutdown (e.g., service
              that already has its own thread)

    AbstractService
              Full control over threads creation


http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
EMF for
                                                  dummies



http://www.flickr.com/photos/bendylan/259110679/
                                                         10
Java Framework and code generation facility


    "Class diagram to Super Java Bean"
                  (My definition)
Ab out those modeling things
‣It’s just about defining the entities/concepts/classes
you will manipulate

‣You can define concepts in several ways
 ‣Annotated Java classes
 ‣XML Schema
 ‣Ecore file
 ‣UML Class diagram

‣You give the input to EMF, and it handles conversion
and generation of the ULTIMATE POJO API
Ab out those modeling things

‣Thin framework layer inserted into your POJO
 ‣you can even hide it ;)

‣The layer is as thin as imaginable and provides high
power-to-weight ratio
 ‣opposite references
 ‣adapters
 ‣edit
 ‣lazy loading
 ‣serialization (REST)
 ‣factory
 ‣reflective calls / metadata generation
Ab out those modeling things

What can you define in Ecore files?

     ‣Package
     ‣Classes
     ‣Attributes
     ‣References
Ab out those modeling things
  ‣Packages
    Logical organization

  ‣Classes
   Classical OO concepts

  ‣Attributes
   Primitive type fields (with cardinality)

  ‣References
   Class type fields (with cardinality), opposite,
   containment
EObject?
The thin layer that changes it all


   Object eGet(EStructuralFeature feature);
   void eSet(EStructuralFeature feature, Object newValue);
   boolean eIsSet(EStructuralFeature feature);
   void eUnset(EStructuralFeature feature);

   EList<EObject> eContents();
   TreeIterator<EObject> eAllContents();
   EObject eContainer();
time to play




                                                   883/
                     /photos/8728229@N07/4592234
http://www.flickr.com


                                                             http://www.flickr.com/photos/squonk
                                                                                               /1715142327/
EMFPath



http://www.flickr.com/photos/eseartista/1604034788/
                                                           11
Path
{
                                 public interface Function<F, T>
   Set of functions and          }
                                     T apply(F from);
                                                                     public interface Predicate<T> {

predicates for EMF objects                                           }
                                                                         boolean apply(T from);




                                Code generators for your
                                  own Ecore models



and few other utility classes
Lazy EObjects containment tree walking

   ‣ parent     (eContainer)

   ‣ ancestor
   ‣ ancestorOrSelf
   ‣ child   (eContents)

   ‣ descendant            (eAllContents)




                                                                         445978272/
   ‣ descendantOrSelf
   ‣ following




                                                           http://www.flickr.com/photos/musiclovenature/1
   ‣ followingSibling
   ‣ preceding
   ‣ precedingSibling

 EObject myObject;
 Collection<EObject> fs = followingSibling.of(myObject);
Common predicates

       Having
       IsKind/IsType
       IsAncestor/IsChild



 public     static   Collection<EObject> demoHaving(Collection<EObject> c) {
 	

 	

   return    Collections2.filter(c,
 	

 	

   	

 	

   Having.feature(EcorePackage.Literals.ENAMED_ELEMENT__NAME,
 	

 	

   	

 	

   StringPredicates.firstUpperCase)
 	

 	

   	

 );
 	

 }
non-EMF functions & predicates
            Strings
length : Function<String, Integer>
toL1Case : Function<String, String>        Comparable
toLowerCase : Function<String, String>
toU1Case : Function<String, String>      Predicates to
toUpperCase : Function<String, String>   test ordering:
trim : Function<String, String>          equal
 replaceAll(Pattern, String)             less than
 replaceAll(String, String)              greater than
 replaceFirst(Pattern, String)           less or equal
 replaceFirst(String, String)            greater or equal
 substring(int)
 substring(int, int)
Ecore API has been Guava-ified
‣ EObject.eResource() is wrapped as a Function in
EObjectPath.eResource

‣ EObject.eIsProxy() is wrapped as a Predicate in
EObjectPath.eIsProxy

‣ EClass.getESuperTypes() is wrapped as a
Function in EClass.eSuperTypes

‣ EReference.isContainment() is wrapped as a
Predicate in ERefrencePath.isContainment
Ecore has been Guava-ified through a generator




             +


    that is available for your own Ecore model
time to play




                                                   883/
                     /photos/8728229@N07/4592234
http://www.flickr.com


                                                             http://www.flickr.com/photos/squonk
                                                                                               /1715142327/
Recap



http://www.flickr.com/photos/loty/326761635/
                                                      12
Wha t you should remember
     about this presentation


1.   Functionnal flavor of collection handling
2.   CharMatcher / Splitter / Joiner
3.   Immutable Collections
4.   Multimap / Multiset / Bimap
5.   MapMaker
6.   EMF is generating plain old POJO
What you  should REALLY remember
 about this presentation

1. Guava is cool, powerful and the definitive
extension to JDK!
2. Never write your own POJO by hand for
now, use EMF!
3. Always generate EMFPath classes to
handle EMF objects!

      http://code.google.com/p/guava-libraries/
        http://code.google.com/p/guava-osgi/
           http://eclipse.org/modeling/emf/
http://code.google.com/a/eclipselabs.org/p/emfpath/
http://www.flickr.com/photos/wwworks/4759535950/




Q&A

More Related Content

What's hot

JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistAnton Arhipov
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleAnton Arhipov
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to missAndres Almiray
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingAnton Arhipov
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistAnton Arhipov
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistAnton Arhipov
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationIvan Dolgushin
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습DoHyun Jung
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.JustSystems Corporation
 
Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Omar Miatello
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code ExamplesNaresh Chintalcheru
 
Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02Omar Miatello
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicGraham Dumpleton
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Sungchul Park
 

What's hot (20)

Google Guava
Google GuavaGoogle Guava
Google Guava
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to miss
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
 

Similar to Google Guava & EMF @ GTUG Nantes

JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...Guillaume Laforge
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
 
Evolving The Java Language
Evolving The Java LanguageEvolving The Java Language
Evolving The Java LanguageQConLondon2008
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's testsSean P. Floyd
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application FrameworkJady Yang
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applicationsrohitnayak
 
Art & music vs Google App Engine
Art & music vs Google App EngineArt & music vs Google App Engine
Art & music vs Google App Enginethomas alisi
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaKonrad Malawski
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingAndres Almiray
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyJames Williams
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Functional Programming in Groovy
Functional Programming in GroovyFunctional Programming in Groovy
Functional Programming in GroovyEvgeny Goldin
 
Best Practices for Front-End Django Developers
Best Practices for Front-End Django DevelopersBest Practices for Front-End Django Developers
Best Practices for Front-End Django DevelopersChristine Cheung
 
Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code EffectivelyAndres Almiray
 

Similar to Google Guava & EMF @ GTUG Nantes (20)

JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
 
Svcc Groovy Testing
Svcc Groovy TestingSvcc Groovy Testing
Svcc Groovy Testing
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Evolving The Java Language
Evolving The Java LanguageEvolving The Java Language
Evolving The Java Language
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
Test Driven In Groovy
Test Driven In GroovyTest Driven In Groovy
Test Driven In Groovy
 
EMFPath
EMFPathEMFPath
EMFPath
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applications
 
Art & music vs Google App Engine
Art & music vs Google App EngineArt & music vs Google App Engine
Art & music vs Google App Engine
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Functional Programming in Groovy
Functional Programming in GroovyFunctional Programming in Groovy
Functional Programming in Groovy
 
Best Practices for Front-End Django Developers
Best Practices for Front-End Django DevelopersBest Practices for Front-End Django Developers
Best Practices for Front-End Django Developers
 
Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code Effectively
 

More from mikaelbarbero

Kubernetes 101 - A Cluster Operating System
Kubernetes 101 - A Cluster Operating SystemKubernetes 101 - A Cluster Operating System
Kubernetes 101 - A Cluster Operating Systemmikaelbarbero
 
Language Server Protocol - Why the Hype?
Language Server Protocol - Why the Hype?Language Server Protocol - Why the Hype?
Language Server Protocol - Why the Hype?mikaelbarbero
 
What's new in Eclipse Oxygen (Devoxx France 2017)
What's new in Eclipse Oxygen (Devoxx France 2017)What's new in Eclipse Oxygen (Devoxx France 2017)
What's new in Eclipse Oxygen (Devoxx France 2017)mikaelbarbero
 
The Eclipse IDE: What's new in the 2017 release?
The Eclipse IDE: What's new in the 2017 release?The Eclipse IDE: What's new in the 2017 release?
The Eclipse IDE: What's new in the 2017 release?mikaelbarbero
 
What every Eclipse developer should know about progress reporting and job can...
What every Eclipse developer should know about progress reporting and job can...What every Eclipse developer should know about progress reporting and job can...
What every Eclipse developer should know about progress reporting and job can...mikaelbarbero
 
The Eclipse IDE - The Force Awakens (Devoxx France 2016)
The Eclipse IDE - The Force Awakens (Devoxx France 2016)The Eclipse IDE - The Force Awakens (Devoxx France 2016)
The Eclipse IDE - The Force Awakens (Devoxx France 2016)mikaelbarbero
 
Sirius: Graphical Editors for your DSLs
Sirius: Graphical Editors for your DSLsSirius: Graphical Editors for your DSLs
Sirius: Graphical Editors for your DSLsmikaelbarbero
 
Modeling in a Team Environment with EMF Compare and EGit
Modeling in a Team Environment with EMF Compare and EGitModeling in a Team Environment with EMF Compare and EGit
Modeling in a Team Environment with EMF Compare and EGitmikaelbarbero
 
Diff and Merge with Ease: EMF Compare
Diff and Merge with Ease: EMF CompareDiff and Merge with Ease: EMF Compare
Diff and Merge with Ease: EMF Comparemikaelbarbero
 
Eclipse simultaneous release in a nutshell
Eclipse simultaneous release in a nutshellEclipse simultaneous release in a nutshell
Eclipse simultaneous release in a nutshellmikaelbarbero
 
OSGi: Don't let me be Misunderstood
OSGi: Don't let me be MisunderstoodOSGi: Don't let me be Misunderstood
OSGi: Don't let me be Misunderstoodmikaelbarbero
 
EMF.Edit the Force Unleashed!
EMF.Edit the Force Unleashed!EMF.Edit the Force Unleashed!
EMF.Edit the Force Unleashed!mikaelbarbero
 
EMF Compare 2.0: Scaling to Millions (updated)
EMF Compare 2.0: Scaling to Millions (updated)EMF Compare 2.0: Scaling to Millions (updated)
EMF Compare 2.0: Scaling to Millions (updated)mikaelbarbero
 
EMFCompare 2.0: Scaling to Millions
EMFCompare 2.0: Scaling to MillionsEMFCompare 2.0: Scaling to Millions
EMFCompare 2.0: Scaling to Millionsmikaelbarbero
 
3mf infinity-and-beyond
3mf infinity-and-beyond3mf infinity-and-beyond
3mf infinity-and-beyondmikaelbarbero
 
Eclipseconeurope 2011 - EMFCompare Improvements
Eclipseconeurope 2011 - EMFCompare ImprovementsEclipseconeurope 2011 - EMFCompare Improvements
Eclipseconeurope 2011 - EMFCompare Improvementsmikaelbarbero
 
5M lines of code migration
5M lines of code migration5M lines of code migration
5M lines of code migrationmikaelbarbero
 
Generating an Android App with Acceleo (Eclipse Summit Europe 2010)
Generating an Android App with Acceleo (Eclipse Summit Europe 2010)Generating an Android App with Acceleo (Eclipse Summit Europe 2010)
Generating an Android App with Acceleo (Eclipse Summit Europe 2010)mikaelbarbero
 

More from mikaelbarbero (18)

Kubernetes 101 - A Cluster Operating System
Kubernetes 101 - A Cluster Operating SystemKubernetes 101 - A Cluster Operating System
Kubernetes 101 - A Cluster Operating System
 
Language Server Protocol - Why the Hype?
Language Server Protocol - Why the Hype?Language Server Protocol - Why the Hype?
Language Server Protocol - Why the Hype?
 
What's new in Eclipse Oxygen (Devoxx France 2017)
What's new in Eclipse Oxygen (Devoxx France 2017)What's new in Eclipse Oxygen (Devoxx France 2017)
What's new in Eclipse Oxygen (Devoxx France 2017)
 
The Eclipse IDE: What's new in the 2017 release?
The Eclipse IDE: What's new in the 2017 release?The Eclipse IDE: What's new in the 2017 release?
The Eclipse IDE: What's new in the 2017 release?
 
What every Eclipse developer should know about progress reporting and job can...
What every Eclipse developer should know about progress reporting and job can...What every Eclipse developer should know about progress reporting and job can...
What every Eclipse developer should know about progress reporting and job can...
 
The Eclipse IDE - The Force Awakens (Devoxx France 2016)
The Eclipse IDE - The Force Awakens (Devoxx France 2016)The Eclipse IDE - The Force Awakens (Devoxx France 2016)
The Eclipse IDE - The Force Awakens (Devoxx France 2016)
 
Sirius: Graphical Editors for your DSLs
Sirius: Graphical Editors for your DSLsSirius: Graphical Editors for your DSLs
Sirius: Graphical Editors for your DSLs
 
Modeling in a Team Environment with EMF Compare and EGit
Modeling in a Team Environment with EMF Compare and EGitModeling in a Team Environment with EMF Compare and EGit
Modeling in a Team Environment with EMF Compare and EGit
 
Diff and Merge with Ease: EMF Compare
Diff and Merge with Ease: EMF CompareDiff and Merge with Ease: EMF Compare
Diff and Merge with Ease: EMF Compare
 
Eclipse simultaneous release in a nutshell
Eclipse simultaneous release in a nutshellEclipse simultaneous release in a nutshell
Eclipse simultaneous release in a nutshell
 
OSGi: Don't let me be Misunderstood
OSGi: Don't let me be MisunderstoodOSGi: Don't let me be Misunderstood
OSGi: Don't let me be Misunderstood
 
EMF.Edit the Force Unleashed!
EMF.Edit the Force Unleashed!EMF.Edit the Force Unleashed!
EMF.Edit the Force Unleashed!
 
EMF Compare 2.0: Scaling to Millions (updated)
EMF Compare 2.0: Scaling to Millions (updated)EMF Compare 2.0: Scaling to Millions (updated)
EMF Compare 2.0: Scaling to Millions (updated)
 
EMFCompare 2.0: Scaling to Millions
EMFCompare 2.0: Scaling to MillionsEMFCompare 2.0: Scaling to Millions
EMFCompare 2.0: Scaling to Millions
 
3mf infinity-and-beyond
3mf infinity-and-beyond3mf infinity-and-beyond
3mf infinity-and-beyond
 
Eclipseconeurope 2011 - EMFCompare Improvements
Eclipseconeurope 2011 - EMFCompare ImprovementsEclipseconeurope 2011 - EMFCompare Improvements
Eclipseconeurope 2011 - EMFCompare Improvements
 
5M lines of code migration
5M lines of code migration5M lines of code migration
5M lines of code migration
 
Generating an Android App with Acceleo (Eclipse Summit Europe 2010)
Generating an Android App with Acceleo (Eclipse Summit Europe 2010)Generating an Android App with Acceleo (Eclipse Summit Europe 2010)
Generating an Android App with Acceleo (Eclipse Summit Europe 2010)
 

Recently uploaded

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Recently uploaded (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Google Guava & EMF @ GTUG Nantes

  • 1. Google Guava & Eclipse Modeling Framework 2011/04/26 Mikaël Barbero
  • 3. About me ‣ Modeling consultant ‣ Research engineer ‣ Trainer ‣ Conference Speaker ‣ Language guy ;) ‣ Eclipse committer ‣ Guava-OSGi packager ‣ EMFPath lead
  • 4. Paris Nantes
  • 7.
  • 8.
  • 9.
  • 10.
  • 12. Guava Overview http://www.flickr.com/photos/slowburn/2986303105/ 2
  • 14.
  • 15. About Guava Java library used Superset of internally @ Google Google for years Collections
  • 16. About Guava Apache License v2 http://www.apache.org/licenses/LICENSE-2.0
  • 17. About Guava s s ti on ti on c lle llec Co 5 Co a r03 a r08 gle v0. gle v1 uav uav G oo G oo G G 2007 2008 2009 2010 2011 Frequent releases (quarterly base) Latest release (r09): April, 7th
  • 18.
  • 19.
  • 20. Why using Guava? Simp lexity http://www.flickr.com/photos/gio_vencato/4941064345/
  • 21. Why using Guava? http://www.flickr.com/photos/reway2007/3300379295/
  • 22. Why using Guava? Mainstream? http://www.flickr.com/photos/funtik/1175522045/
  • 23. Why using Guava? Helping others http://www.flickr.com/photos/thearches/4381959041/
  • 24. Inside Guava IO Networking Concurrency Primitive types Collections GWT compatibility is tested (see @GwtCompatible)
  • 25. Comparison with Apache Commons Better Better More Modern Designed Supported Best practices Actively Java 5 developed and patterns (- commons 3.0) Respects JDK Google Orthogonality contracts (@Beta to test designs) depends on it (e.g., Google Guice) http://stackoverflow.com/questions/4542550/what-are-the-big-improvements-between-guava-and-apache-equivalent-libraries
  • 27. Corest of the core http://www.flickr.com/photos/27384147@N02/5211738745/ 3
  • 28. Objects class public class Person { final String name, nickname; final Movie favMovie; @Override public boolean equals(Object object) { if (object instanceof Person) { Person that = (Person) object; return Objects.equal(this.name, that.name) && Objects.equal(this.nickname, that.nickname) && Objects.equal(this.favMovie, that.favMovie); } return false; } @Override public int hashCode() { return Objects.hashCode(name, nickname, favMovie); } } Example from http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 29. Objects class public class Person { final String name, nickname; final Movie favMovie; //... @Override public String toString() { return Objects.toStringHelper(this) .add("name", name) .add("nickname", nickname) .add("favMovie", favMovie) .toString(); } public String preferredName() { return Objects.firstNonNull(nickname, name); } } Example from http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 30. Preconditions Defensive coding if (state != State.PLAYABLE) { throw new IllegalStateException( "Can't play movie; state is " + state); } Preconditions.checkState(state == State.PLAYABLE, "Can't play movie; state is %s", state); Example from http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 31. Preconditions Defensive coding public void setRating(StarRating rating) { if (rating == null) { throw new NullPointerException(); } this.rating = rating; } public void setRating(StarRating rating) { this.rating = checkNotNull(rating); } Example from http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 32. Equivalences strategies public interface Equivalence<T> { boolean equivalent(@Nullable T a, @Nullable T b); int hash(@Nullable T t); } Equivalence equals = Equivalences.equals(); Equivalence identity = Equivalences.identity(); Equivalence<String> elementEquivalence = ...; Equivalence<Iterable<String>> pairwise = Equivalences.pairwise(elementEquivalence); Collection<String> c1, c2; pairwise.equivalent(c1, c2);
  • 33. Suppliers public interface Supplier<T> { T get(); } Supplier<String> s = ...; Supplier<String> memoizing = Suppliers.memoize(s); Supplier<String> expiring = Suppliers.memoizeWithExpiration(s, 100, TimeUnit.SECONDS); Supplier<String> ofInstance = Suppliers.ofInstance("Always returning");
  • 34. Throwables Throwables.getCausalChain(throwable); Throwables.getRootCause(throwable); Throwables.getStackTraceAsString(throwable); Throwables.propagateIfInstanceOf(throwable, IOException.class); Throwables.propagateIfPossible(throwable); try { someMethodThatCouldThrowAnything(); } catch (IKnowWhatToDoWithThisException e) { handle(e); } catch (Throwable t) { Throwables.propagateIfPossible(t); throw new RuntimeException("unexpected", t); }
  • 35. @Annotation @Beta @VisibleForTesting @GwtCompatible @GwtIncompatible
  • 37. CharMatcher +1 StringUtil example: allAscii, collapse, collapseControlChars, collapseWhitespace, indexOfChars, lastIndexNotOf, numSharedChars, removeChars, removeCrLf, replaceChars, retainAllChars, strip, stripAndCollapse, stripNonDigits, ... Partial cross product of two notions: (a) what's a "matching" character? (b) what to do with those matching characters? CharMatcher: An instance of this type represents part (a), and the operation you invoke on it represents part (b). http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 38. Getting a CharMatcher CharMatcher.WHITESPACE (Unicode) CharMatcher.JAVA_DIGIT Predefined constants CharMatcher.ASCII (examples) CharMatcher.ANY Factory methods CharMatcher.is('x') (examples) CharMatcher.isNot('_') CharMatcher.oneOf("aeiou").negate() CharMatcher.inRange('a', 'z').or(inRange('A', 'Z')) Subclass CharMatcher, implement matches(char c) Now check out all that you can do... http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 39. Using your CharMatcher ‣ boolean matchesAllOf(CharSequence) ‣ boolean matchesAnyOf(CharSequence) ‣ boolean matchesNoneOf(CharSequence) ‣ int indexIn(CharSequence, int) ‣ int lastIndexIn(CharSequence, int) ‣ int countIn(CharSequence) ‣ String removeFrom(CharSequence) ‣ String retainFrom(CharSequence) ‣ String trimFrom(CharSequence) ‣ String trimLeadingFrom(CharSequence) ‣ String trimTrailingFrom(CharSequence) ‣ String collapseFrom(CharSequence, char) ‣ String trimAndCollapseFrom(CharSequence, char) ‣ String replaceFrom(CharSequence, char) http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 40. Using your CharMatcher String string = "Scream 4"; CharMatcher matcher = CharMatcher.JAVA_LETTER_OR_DIGIT; int count = matcher.countIn(string); System.out.println("Letter or digit count: "+count); // Letter or digit count: 7 System.out.println(matcher.matchesAllOf("scream")); // true System.out.println(matcher.matchesAllOf("scream ")); // false System.out.println(matcher.matchesNoneOf("_?=)(")); // true http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-1.html
  • 41. Splitter +1 JDK has splitter ‣ regular expression ‣ result as an array ‣ its way of handling empty pieces (which is very strange) Mini-puzzler ",a,,b,".split(",") returns... (a) "", "a", "", "b", "" (b) null, "a", null, "b", null (c) "a", null, "b" (d) "a", "b" (e) None of the above http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 42. Splitter e_s_jones/5060802981/ http://www.flickr.com/photos/terenc Splitter is String.split() on steroids http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 43. Splitter The default behavior is simplistic: //yields [" foo", " ", "bar", " quux", ""] Splitter.on(',').split(" foo, ,bar, quux,"); If you want extra features, ask for them! //yields ["foo", "bar", "quux"] Splitter.on(',') .trimResults() .omitEmptyStrings() .split(" foo, ,bar, quux,"); http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 44. Ascii, Charsets Ascii list of bytes constants for each Char between 0x00 & 0x7F Charsets by G uaranteed to be supported ons al l Java platform implementati No more ‣Charsets.ISO_8859_1; try { bytes = string.getBytes("UTF-8"); ‣Charsets.US_ASCII; } catch (UnsupportedEncodingException e) { ‣Charsets.UTF_16; // how can this possibly happen? ‣Charsets.UTF_16BE; throw new AssertionError(e); } ‣Charsets.UTF_16LE; ‣Charsets.UTF_8;
  • 45. Strings String str = Strings.emptyToNull(s); String str = Strings.nullToEmpty(s); boolean b = Strings.isNullOrEmpty(s);
  • 46. CaseFormat ‣ LOWER_CAMEL ‣ Java variable naming convention, e.g., "lowerCamel". ‣ LOWER_HYPHEN ‣ Hyphenated variable naming convention, e.g., "lower-hyphen". ‣ LOWER_UNDERSCORE ‣ C++ variable naming convention, e.g., "lower_underscore". ‣ UPPER_CAMEL ‣ Java and C++ class naming convention, e.g., "UpperCamel". ‣ UPPER_UNDERSCORE ‣ Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE". E xample CaseFormat.to(CaseFormat.UPPER_UNDERSCORE, s);
  • 48. Ordering { Co mparator<T> publ ic interface ); int compare(T, T abstract equals(Objec t); ean a bstract bool } Comparator is easy to implement, but a pain to use Push the Comparator<T> interface to the next level http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
  • 49. Ordering public class Employee implements Comparable<Employee> { private final int id; private final String name; private final int yearsOfService; public Employee(int id, String name, int yearsOfService) { this.id = id; this.name = name; this.yearsOfService = yearsOfService; } Simple public int getId() { return id; } public String getName() { return name; } data class public int getYearsOfService() { return yearsOfService; } @Override public int compareTo(Employee employee) { return this.getName().compareTo(employee.getName()); } @Override public String toString() { return Objects.toStringHelper(this) .add("id", id) .add("name", name) .add("years of service", yearsOfService) .toString(); } } http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
  • 50. Ordering Employee anakinSk = new Employee(4, "Anakin Skywalker", 4); Employee darthVader = new Employee(3, "Darth Vader", 5); Employee hanSolo = new Employee(2, "Han Solo", 10); List <Employee> employeeList = Lists.newArrayList(anakinSk, hanSolo, darthVader); System.out.println("employee list: "+employeeList); employee list: [Employee{id=4, name=Anakin Skywalker, years of service=4}, Employee{id=2, name=Han Solo, years of service=10}, Employee {id=3, name=Darth Vader, years of service=5}] http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
  • 51. Ordering Define your own Comparator Comparator<Employee> yearsComparator = new Comparator<Employee>() { @Override public int compare(Employee employee1, Employee employee2) { return (employee1.getYearsOfService() - employee2 .getYearsOfService()); } }; Comparator<Employee> idComparator = new Comparator<Employee>() { @Override public int compare(Employee employee1, Employee employee2) { return (employee1.getId() - employee2.getId()); } }; http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
  • 52. Ordering Create an Ordering from a Comparator Ordering<Employee> orderUsingYearsComparator = Ordering.from(yearsComparator); Use your ordering, e.g. to sort List<Employee> sortedCopy = orderUsingYearsComparator.sortedCopy(employeeList); System.out.println("sorted copy: " + sortedCopy); sorted copy: [Employee{id=4, name=Anakin Skywalker, years of service=4}, Employee{id=3, name=Darth Vader, years of service=5}, Employee{id=2, name=Han Solo, years of service=10}] http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
  • 53. Ordering toString() ordering Ordering<Object> toStringOrdering = Ordering.usingToString(); Natural ordering (Comparable<T>) Ordering<Employee> natural = Ordering.natural(); http://scaramoche.blogspot.com/2010/05/googles-guava-library-tutorial-part-2.html
  • 54. What you can do with Ordering ‣ Ordering.min(Iterable<E>) ‣ Ordering.max(Iterable<E>) ‣ Ordering.leastOf(Iterable<E>, int) ‣ Ordering.greatestOf(Iterable<E>, int) ‣ Ordering.isOrdered(Iterable<? extends T>) ‣ Ordering.isStrictlyOrdered(Iterable<? extends T>) ‣ Ordering.binarySearch(List<? extends T>, T)
  • 55. What you can do with Ordering ‣ Ordering.sortedCopy(Iterable<E>) ‣ Ordering.immutableSortedCopy(Iterable<E>) new TreeSet( Collection) Better than card duplicate s elements Do not dis Performed sort is stable
  • 56. Ordering is configurable ‣ Ordering.reverse() ‣ Ordering.lexicographical() ‣ Ordering.nullsFirst() ‣ Ordering.nullsLast() ‣ Ordering.reverse() Lexicographical returns an Ordering on Iterable of T [] < [1] < [1, 1] < [1, 2] < [2]
  • 57. ObjectArrays ‣ concat(T, T[]) ‣ concat(T[], T) ‣ concat(T[], T[], Class<T>) ‣ newArray(Class<T>, int) ‣ newArray(T[], int)
  • 58. Multiset & Multimap Historically, multisets (aka bags) and multimaps emulated atop maps Multimap = Map<K, List<V>> Multiset = Map<K, Integer>
  • 59. When to use Multiset? ‣"I kinda want a Set except I can have duplicates" ‣ card games example ‣ changing to List sacrifices contains() performance ‣"Are these Lists equal, ignoring order?" ‣ write a utility method for this? Histograms ‣"What distinct tags am I using on my blog, and how many times do I use each one?" Multiset performance varies by the number of distinct elements, not total size. http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 60. Multiset Ever done this? 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 "java" tag: Usage tags.containsKey("java") ? tags.get("java") : 0; total count: // oh crap... http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 61. Multiset Would you rather do this? Multiset<String> tags = HashMultiset.create(); for (BlogPost post : getAllBlogPosts()) { tags.addAll(post.getTags()); } distinct tags: tags.elementSet(); Usage count for "java" tag: tags.count("java"); (hurrah) total count: tags.size(); http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 62. Multiset API ‣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. http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 63. Multiset API ‣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); http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 64. Multiset implementations +1 ImmutableMultiset HashMultiset LinkedHashMultiset TreeMultiset EnumMultiset ConcurrentHashMultiset http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 65. When to use Multimap? 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); } http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 66. When to use Multimap? 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 previous slide is ‣Verbose ‣Bug-prone ‣Limited in functionality ‣Using the wrong abstraction http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 67. More about Multimap 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]} http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 68. 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... http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 69. Multimap, 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; } http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 70. Multimap, after 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(). http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 71. Multimap API 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() http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 72. Multimap implementations +1 ImmutableMultimap ImmutableListMultimap ImmutableSetMultimap ArrayListMultimap HashMultimap LinkedHashMultimap LinkedListMultimap TreeMultimap ListMultimap SetMultimap SortedSetMultimap http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 73. BiMap +1 aka unique-valued map 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! http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 74. BiMap Implementations ImmutableBiMap HashBiMap EnumBiMap EnumHashBiMap http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 75. Constrained Collections/Maps public interface Constraint<E> { E checkElement(E element); } //... public Object checkElement(Object element) { if (element == null) { throw new NullPointerException(); } return element; } Constraints.n otNull() //...
  • 76. Constrained Collections/Maps Constraints. constrainedCollection(Collection<E>, Constraint<? super E>) constrainedList(List<E>, Constraint<? super E>) constrainedMultiset(Multiset<E>, Constraint<? super E>) constrainedSet(Set<E>, Constraint<? super E>) constrainedSortedSet(SortedSet<E>, Constraint<? super E>)
  • 77. MapMaker +1 A ConcurrentMap builder, providing any combination of these features: ‣Soft or weak keys ‣Soft or weak values ‣Timed expiration ‣On-demand computation of values Far more powerful, easy to use than WeakHashMap Concurrent on-demand computation is really hard
  • 78. MapMaker ConcurrentMap<User, Graph> recommendations = new MapMaker() .concurrencyLevel(4) .softKeys() .weakValues() .maximumSize(10000) .expireAfterWrite(10, TimeUnit.MINUTES) .makeComputingMap( new Function<User, Graph>() { public Graph apply(User user) { return createExpensiveGraph(user); } });
  • 79. Forwarding Object/Collections Abstract implementations of existing types delegating all method calls to its delegate() protected abstract Object delegate(); Decorator pattern without the burden ;)
  • 80. Forwarding Collections ForwardingCollection ForwardingMultiset ForwardingConcurrentMap ForwardingObject ForwardingIterator ForwardingQueue ForwardingList ForwardingSet ForwardingListIterator ForwardingSetMultimap ForwardingListMultimap ForwardingSortedMap ForwardingMap ForwardingSortedSet ForwardingMapEntry ForwardingSortedSetMultimap ForwardingMultimap ForwardingTable
  • 81. Static utilities In classes with name ending with an s ‣ Lists ‣ Maps ‣ Multimaps ‣ Multisets ‣ Sets ‣ SortedMaps ‣ Tables ‣ Iterators ‣ Iterables ‣ Collections2
  • 82. Static factories methods +1 Rather than typing Map<String, Class<? extends Handler>> m = new HashMap<String, Class<? extends Handler>>(); you type Map<String, Class<? extends Handler>> m2 = Maps.newHashMap(); Guava provides these for JDK collections and for Guava collections (Multi*...) With overloads to accept Iterables to copy elements from
  • 83. Maps as index +1 Maps.uniqueIndex() Map<Integer, Employee> m = Maps.uniqueIndex(values, new Function<Employee, Integer>() { @Override public Integer apply(Employee input) { return input.getId(); } });
  • 84. Multimaps as index +1 Multimaps.index() Multimap<Integer, Employee> m = Multimaps.index(values, new Function<Employee, Integer>() { @Override public Integer apply(Employee input) { return input.getYearsOfService(); } });
  • 85. Map differences +1 So you want to compute the differences between two maps Guava has it too Maps.difference( Map<? extends K,? extends V>, Map<? extends K,? extends V>) Difference is an immutable snapshot of the state of the maps at the time this method is called
  • 86. MapDifference API Map<K,V> entriesInCommon() Map<K,V> entriesOnlyOnLeft() Map<K,V> entriesOnlyOnRight() Map<K,MapDifference.ValueDifference<V>> entriesDiffering() ValueDifference API V leftValue() V rightValue()
  • 87. Sets union/intersection/difference +1 difference(Set<E>, Set<?>) symmetricDifference(Set<? extends E>, Set<? extends E>) union(Set<? extends E>, Set<? extends E>) intersection(Set<E>, Set<?>) Returns Sets.SetView<E>
  • 88. Sets combinations Set<Set<E>> powerSet(Set<E>) while the power set of a set with size n is of size 2^n, its memory usage is only O(n) Set<List<B>> cartesianProduct( List<? extends Set<? extends B>>) while the cartesian product of sets of size m, n, p is a set of size m x n x p, its actual memory consumption is much smaller (m + n + p)
  • 89. Immutable collections JDK has Collections.unmodifiableFoo wrappers ‣Unmodifiable - you can't change it ‣Immutable - it can never change, no matter what ‣Immutability is tasty! ‣See Effective Java Item 15 for some of the many reasons http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 90. Immutable collections +1 ImmutableList ImmutableSet ImmutableMap ImmutableSortedMap ImmutableSortedSet ImmutableMultiset ImmutableMultimap ImmutableListMultimap ImmutableSetMultimap ImmutableBiMap http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 91. Immutable collections JDK wrappers still useful for unmodifiable views of changing data. But for most purposes, use Guava’s: ‣Brand-new, standalone implementations ‣Immutability guaranteed! ‣Very easy to use ‣See following slides ‣Slightly faster ‣Null hostile ‣Use less memory ‣Sometimes far less (ImmutableSet, factor of 2-3x) http://google-collections.googlecode.com/files/google-collections-svgtug-2008-08-06.pdf
  • 92. Immutable collections Factory methods ImmutableXXX.of() immutable empty XXX ImmutableXXX.of(E) singletons ImmutableXXX.of(E, E) ImmutableXXX.of(E, E, E, E...) ImmutableXXX.copyOf(Iterable) ImmutableXXX.copyOf(Iterator) small maps only (up ImmutableMap.of(1, "one", 2, "two") to 5 key/value pairs) ImmutableMap.copyOf(Map) Builder pattern otherwise
  • 93. Constants Sets 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); } http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 94. Constants Sets 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. http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 95. Constants Sets 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 http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 96. Constants Maps public static final Map<String, Integer> ENGLISH_TO_INT; static { Map<String, Integer> map = new LinkedHashMap<String, Integer>(); map.put("four", 4); map.put("eight", 8); map.put("fifteen", 15); map.put("sixteen", 16); map.put("twenty-three", 23); map.put("forty-two", 42); ENGLISH_TO_INT = Collections.unmodifiableMap(map); } http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 97. Constants Maps public static final ImmutableMap<String, Integer> ENGLISH_TO_INT = ImmutableMap.<String,Integer>builder() .put("four", 4) .put("eight", 8) .put("fifteen", 15) .put("sixteen", 16) Empowering the .put("twenty-three", 23) Builder Pattern! .put("forty-two", 42) .build(); http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 98. Table @Beta since r07 Collection with columns and rows No more Map<T1, Map<T2,T3>> Table<R,C,V> composed of Table.Cell<R,C,V> Tables.transpose() (flips row and column keys) 6 views 2 impl. Set<Table.Cell<R,C,V>> cellSet() Map<R,V> column(C) HashBasedTable Set<C> columnKeySet() TreeBasedTable Map<C,Map<R,V>> columnMap() Map<C,V> row(R) Set<R> rowKeySet() Map<R,Map<C,V>> rowMap()
  • 100. in com.google.common.base package public interface Predicate<T> { Predicate<T> to filter boolean apply(T from); out a collection } { public interface Function<F, T> T apply(F from); Function<F, T> to } transform a collection
  • 101. in com.google.common.collect package Iterables.filter() Iterators.filter() Collections2.filter() Sets.filter() http://www.flickr.com/photos/luis_is_rubbish_at_photography/5464233571/
  • 102. 24 42 13 7 128 public static void demo(Collection<Integer> c) { Predicate<Integer> isEven = new Predicate<Integer>() { @Override public boolean apply(Integer input) { return (input.intValue() % 2 == 0); } }; Collection<Integer> fCol = Collections2.filter(c, isEven); } 24 42 128
  • 103. in com.google.common.collect package Iterables.transform() Iterators.transform() Collections2.transform() Lists.transform() http://www.flickr.com/photos/brotherxii/2203037632 /
  • 104. Apple Orange Banana Kiwi Pear public void demo(Collection<String> c) { Function<String, String> toUpperCase = new Function<String, String>() { @Override public String apply(String input) { return input.toUpperCase(); } }; Collection<String> tCol = Collections2.transform(c, toUpperCase); } APPLE ORANGE BANANA KIWI PEAR
  • 105. Beware of lazyness http://www.flickr.com/photos/torek/2467519466/
  • 106. Copy! Lists.newArrayList() Lists.newLinkedList() Sets.newHashSet() Sets.newLinkedHashSet() Sets.newTreeSet() or make it immutable... ImmutableList.copyOf() ImmutableSet.copyOf() http://www.flickr.com/photos/visionnewspaper/314107094/
  • 107. Compose and combine http://www.flickr.com/photos/jgscism/5484243543/ Functions compose forPredicate Predicates and or not compose
  • 108. Compose and combine Function<String, String> toUpper = new Function<String, String>() { @Override public String apply(String input) { return input.toUpperCase(); } }; Function<Integer, String> toHexString = new Function<Integer, String>() { @Override public String apply(Integer input) { return Integer.toHexString(input.intValue()); } }; Function<Integer, String> toUpperHexString = Functions.compose(toUpper, toHexString);
  • 109. Compose and combine Predicate<String> isEmpty = new Predicate<String>() { @Override public boolean apply(String input) { return input.length() == 0; // isEmpty() is Java6 only } }; Predicate<Object> isNull = new Predicate<Object>() { @Override public boolean apply(Object input) { return input == null; } }; Predicate<String> nullOfEmpty = Predicates.or(isNull, isEmpty);
  • 110. Maps transform & filter Maps.filterEntries() Maps.filterKeys() Maps.filterValues() Maps.transformEntries() Maps.transformValues() Equivalence for Multimaps
  • 112. common.primitives package that helps you work with the primitive types int, long, double, float, char, byte, short, and boolean If you need help doing a primitive task: 1. check the wrapper class (e.g. java.lang.Integer) 2. check java.util.Arrays 3. check com.google.common.primitives 4. it might not exist! http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 113. common.primitives Contains the classes Booleans, Each has the exact same structure Bytes, (but has only the subset of operations that make sense for its type). Chars, Doubles, Floats, Many of the byte-related methods Ints, have alternate versions in the classes Longs and (wait for it) SignedBytes and UnsignedBytes. (Bytes are peculiar...) Shorts Guava doesn't do primitive-based collections; try fastutil, or trove4j, or... http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 114. The big table Method Longs Ints Shorts Chars Doubles Bytes S.Bytes U.Bytes Booleans hashCode x x x x x x x compare x x x x x x x x checkedCast x x x x x saturadCast x x x x x contains x x x x x x indexOf x x x x x x x lastIndexOf x x x x x x x min x x x x x x max x x x x x x concat x x x x x x x join x x x x x x x toArray x x x x x x x asList x x x x x x x lexComparator x x x x x x x toByteArray x x x x fromByteArray x x x x http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 116. common.io 2 key interfaces public interface InputSupplier<T> { T getInput() throws IOException; } Typically: public interface OutputSupplier<T> { InputSupplier<InputStream>, OutputSupplier<Writer>, etc. T getOutput() throws IOException; } This lets all Guava’s utilities be useful for many kinds of I/O. Terminology ‣ byte stream means "InputStream or OutputStream" ByteStreams utilities class ‣ char stream means "Reader or Writer." CharStreams utilities class http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 117. ByteStreams ‣byte[] toByteArray(InputStream) ‣byte[] toByteArray(InputSupplier) ‣void readFully(InputStream, byte[]) ‣void write(byte[], OutputSupplier) ‣long copy(InputStream, OutputStream) ‣long copy(InputSupplier, OutputSupplier) ‣long length(InputSupplier) ‣boolean equal(InputSupplier, InputSupplier) ‣InputSupplier slice(InputSupplier, long, long) ‣InputSupplier join(InputSupplier...) CharStreams is similar, but deals in Reader, Writer, String and CharSequence (often requiring you to specify a Charset). http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 118. Files The Files class works one level higher than ByteStreams and CharStreams byte[] toByteArray(File) void write(byte[], File) void write(CharSequence, File, Charset) long copy(File, File) long copy(InputSupplier, File) long copy(File, OutputSupplier) long copy(File, Charset, Appendable) long move(File, File) boolean equal(File, File) http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 119. More about Files File createTempDir() void deleteDirectoryContents(File) void deleteRecursively(File) long getChecksum(File, Checksum) byte[] getDigest(File, MessageDigest) String readFirstLine(File, Charset) List<String> readLines(File, Charset) T readLines(File, Charset, LineProcessor<T>) String toString(File, Charset) http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 120. Flushab les and Closeables Flushables.flushQuietly(Flushable flushable) Flushables.flush( Flushable flushable, boolean swallowIOException) throws IOException Closeables.closeQuietly(Closeable closeable) Closeables.close( Closeable closeable, boolean swallowIOException) throws IOException Very usefull in finally blocks (avoid nesting try/catch) http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 121. common.net ‣URI Work with literals of: ‣URL ‣@IP (v4/v6) Never cause DNS services to be accessed (JDK does...) HostSpecifier syntactically valid host specifier, suitable for use in a URI InternetDomainName ~RFC 1035, i18n DN InetAddresses utility pertaining to Inet(4|6)Address instances http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
  • 123. Concurrency in Guava Immutable* ConcurrentHashMultiset Multimaps.synchronizedMultimap MapMaker http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 124. comm on.util.concurrent It’s all about Future (as in java.util.concurrent) (never heard of it, go take a nap) "A handle to an in-progress computation." "A promise from a service to supply us with a result." http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 125. Future JDK Future public interface Future<V> { //... V get(); //... } Guava ListenableFuture public interface ListenableFuture<V> extends Future<V> { void addListener(Runnable r, Executor e); } http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 126. ListenableFuture Future with one new method: addListener When the future is done (success, exception, cancellation), the listeners run the killer app: "To serve as a foundation for higher- level abstractions" See Futures http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 127. ListenableFuture When to use? Always. (+) Most Futures methods require it. (+) It's easier than changing to ListenableFuture later. (+) Providers of utility methods won't need to provide Future and ListenableFuture variants of their methods. (−) "ListenableFuture" is lengthier than "Future." (−) Classes like ExecutorService give you a plain Future by default. http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 128. Transform and chain Function<QueryResult, List<Row>> rowsFunction = new Function<QueryResult, List<Row>>() { public List<Row> apply(QueryResult queryResult) { return queryResult.getRows(); } }; Future<QueryResult> queryFuture = ...; Future<List<Row>> rowsFuture = transform(queryFuture, rowsFunction); http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 129. Transform and chain Function<RowKey, ListenableFuture<QueryResult>> queryFunction = new Function<RowKey, ListenableFuture<QueryResult>>() { public ListenableFuture<QueryResult> apply(RowKey rowKey) { return dataService.read(rowKey); } }; ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query); ListenableFuture<QueryResult> queryFuture = chain(rowKeyFuture, queryFunction); http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 130. Futures Got a Iterable<Future<V>>? Decide what you want: Future of List<V> Futures.allAsList() List of Future<V> Futures.successfulAsList() http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 131. Executors MoreExecutors.sameThreadExecutor for quick tasks that can run inline MoreExecutors.getExitingExecutorService for "half-daemon" threads UncaughtExceptionHandlers.systemExit for exiting after unexpected errors ThreadFactoryBuilder new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("WebRequestHandler-%d") .build(); http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 132. Services "An object with an operational state, plus asynchronous start() and stop() lifecycle methods to transfer into and out of this state." Example: web servers, RPC servers, monitoring initialization, ... http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 133. Services AbstractExecutionThreadService One thread automatically created for you at startup AbstractIdleService Thread only needed for startup and shutdown (e.g., service that already has its own thread) AbstractService Full control over threads creation http://guava-libraries.googlecode.com/files/guava-concurrent-slides.pdf
  • 134. EMF for dummies http://www.flickr.com/photos/bendylan/259110679/ 10
  • 135. Java Framework and code generation facility "Class diagram to Super Java Bean" (My definition)
  • 136. Ab out those modeling things ‣It’s just about defining the entities/concepts/classes you will manipulate ‣You can define concepts in several ways ‣Annotated Java classes ‣XML Schema ‣Ecore file ‣UML Class diagram ‣You give the input to EMF, and it handles conversion and generation of the ULTIMATE POJO API
  • 137. Ab out those modeling things ‣Thin framework layer inserted into your POJO ‣you can even hide it ;) ‣The layer is as thin as imaginable and provides high power-to-weight ratio ‣opposite references ‣adapters ‣edit ‣lazy loading ‣serialization (REST) ‣factory ‣reflective calls / metadata generation
  • 138. Ab out those modeling things What can you define in Ecore files? ‣Package ‣Classes ‣Attributes ‣References
  • 139. Ab out those modeling things ‣Packages Logical organization ‣Classes Classical OO concepts ‣Attributes Primitive type fields (with cardinality) ‣References Class type fields (with cardinality), opposite, containment
  • 140. EObject? The thin layer that changes it all Object eGet(EStructuralFeature feature); void eSet(EStructuralFeature feature, Object newValue); boolean eIsSet(EStructuralFeature feature); void eUnset(EStructuralFeature feature); EList<EObject> eContents(); TreeIterator<EObject> eAllContents(); EObject eContainer();
  • 141. time to play 883/ /photos/8728229@N07/4592234 http://www.flickr.com http://www.flickr.com/photos/squonk /1715142327/
  • 143. Path
  • 144. { public interface Function<F, T> Set of functions and } T apply(F from); public interface Predicate<T> { predicates for EMF objects } boolean apply(T from); Code generators for your own Ecore models and few other utility classes
  • 145. Lazy EObjects containment tree walking ‣ parent (eContainer) ‣ ancestor ‣ ancestorOrSelf ‣ child (eContents) ‣ descendant (eAllContents) 445978272/ ‣ descendantOrSelf ‣ following http://www.flickr.com/photos/musiclovenature/1 ‣ followingSibling ‣ preceding ‣ precedingSibling EObject myObject; Collection<EObject> fs = followingSibling.of(myObject);
  • 146. Common predicates Having IsKind/IsType IsAncestor/IsChild public static Collection<EObject> demoHaving(Collection<EObject> c) { return Collections2.filter(c, Having.feature(EcorePackage.Literals.ENAMED_ELEMENT__NAME, StringPredicates.firstUpperCase) ); }
  • 147. non-EMF functions & predicates Strings length : Function<String, Integer> toL1Case : Function<String, String> Comparable toLowerCase : Function<String, String> toU1Case : Function<String, String> Predicates to toUpperCase : Function<String, String> test ordering: trim : Function<String, String> equal replaceAll(Pattern, String) less than replaceAll(String, String) greater than replaceFirst(Pattern, String) less or equal replaceFirst(String, String) greater or equal substring(int) substring(int, int)
  • 148. Ecore API has been Guava-ified ‣ EObject.eResource() is wrapped as a Function in EObjectPath.eResource ‣ EObject.eIsProxy() is wrapped as a Predicate in EObjectPath.eIsProxy ‣ EClass.getESuperTypes() is wrapped as a Function in EClass.eSuperTypes ‣ EReference.isContainment() is wrapped as a Predicate in ERefrencePath.isContainment
  • 149. Ecore has been Guava-ified through a generator + that is available for your own Ecore model
  • 150. time to play 883/ /photos/8728229@N07/4592234 http://www.flickr.com http://www.flickr.com/photos/squonk /1715142327/
  • 152. Wha t you should remember about this presentation 1. Functionnal flavor of collection handling 2. CharMatcher / Splitter / Joiner 3. Immutable Collections 4. Multimap / Multiset / Bimap 5. MapMaker 6. EMF is generating plain old POJO
  • 153. What you should REALLY remember about this presentation 1. Guava is cool, powerful and the definitive extension to JDK! 2. Never write your own POJO by hand for now, use EMF! 3. Always generate EMFPath classes to handle EMF objects! http://code.google.com/p/guava-libraries/ http://code.google.com/p/guava-osgi/ http://eclipse.org/modeling/emf/ http://code.google.com/a/eclipselabs.org/p/emfpath/