SlideShare a Scribd company logo
By Jitendra Gosain Google Collections API
Introduction What is Google Collections API? Its a utility API. Its an extension to the Java Collections API. Its a set of new Collection Types and  implementations. Part of the Project called “ Guava ” Requires “ JDK 1.5”
Key Interfaces and Classes
Multimap A collection similar to a Map, but which may associate multiple values with a single key. Keys and values can be null.  Adding a new key-value pair equal to an existing key-value pair has no effect.
HashMultimap Example HashMultimap<Integer, String> hm =  HashMultimap.create (); hm.put(1, &quot;first&quot;);//Add Values to keys hm.put(2, &quot;second&quot;); hm.put(1, &quot;third&quot;); //Same key is added a new value hm.put(1, &quot;fourth&quot;);  //hm is {1=[fourth, third, first], 2=[second]}
HashMultimap Example hm.remove(1,&quot;first&quot;);//{1=[fourth, third], 2=[second]} hm.removeAll(1);//{2=[second]} Multimap safeMultimap = Multimaps. synchronizedMultimap (hm); SetMultimap safeSetMultimap = Multimaps. synchronizedSetMultimap (hm); Map mp = hm. asMap (); //Converts to Java Map
Multiset A Multiset can have duplicates unlike a Java Set.  Also called a “ Bag ”. The total number of occurrences of an element in a multiset is called the  count  of that element.
HashMultiset Example HashMultiset ms = HashMultiset. create (); ms.add(&quot;1&quot;); ms.add(&quot;2&quot;);  ms.add(&quot;1&quot;); ms.add(&quot;3&quot;, 3); //HashMultiset ms is [3 x 3, 2, 1 x 2]
HashMultiset Set emSet = ms. elementSet (); //[3, 2, 1] – Above returns set of distinct elements   ms.remove(&quot;1&quot;, 1); //Set is now [3 x 3, 2, 1] ms.remove(&quot;1&quot;, ms.count(&quot;1&quot;)); //[3 x 3, 2] Set set = new HashSet(); set.add(&quot;2&quot;); ms. retainAll (set); //[2] – Retains the elements of Collection “set”
BiMap A bimap (or &quot; bidirectional map &quot;) is a map that preserves the uniqueness of its values as well as that of its keys and looking up a key from a value is possible .  Also called “ unique-valued map ”.  A HashBiMap and its inverse are both serializable.
BiMap Example HashBiMap<Integer, String> hmBiMap =  HashBiMap. create (); hmBiMap.put(1, &quot;first&quot;); hmBiMap.put(2, &quot;second&quot;); hmBiMap.put(2, “newsecond&quot;); //2 holds this hmBiMap.put(3, &quot;second&quot;);  //Above throws an error (value already present)
BiMap Example hmBiMap. inverse ();  //Above returns the inverse view of this bimap, value mapped to key now. Set set = hmBiMap. values (); //Returns a collection of values of the bimap
ImmutableMap An instance of ImmutableMap contains its own  data that will never change . Provides  read-only  access of data. The Java “Collections.unmodifiableMap” which is a  view  of a separate map which can still change, an instance of ImmutableMap contains its own data and will  never  change. Also called the “ Constant Maps ”.
ImmutableMap Example ImmutableMap<String,Integer> map1 =   new ImmutableMap. Builder <String,Integer>()   .put(&quot;one&quot;, 1)   .put(&quot;two&quot;, 2)   .put(&quot;three&quot;, 3)   . build ();//Build an Immutable map
ImmutableMap Example map1.put(&quot;four&quot;, 4); //Not allowed map1.remove(4); //Not allowed //Above throws “UnsupportedOperationException” map1. containsKey (&quot;one&quot;); //true map1. containsValue (3); //true
ImmutableMap Example Map<String, String> javaMap = new HashMap<String, String>(); javaMap.put(&quot;key1&quot;, &quot;value1&quot;); javaMap.put(&quot;key2&quot;, &quot;value2&quot;); ImmutableMap<String,String> map =  ImmutableMap.of (&quot;key1&quot;, &quot;value1&quot;, &quot;key2&quot;, &quot;value2&quot;);
ImmutableSet An instance of the ImmutableSet contains its own  data that will not change . ImmutableSet set1 = new ImmutableSet. Builder ().add(&quot;1&quot;).add(&quot;2&quot;) .build(); set1.add(“3”); //Its not Allowed set1.remove(“1”); //Not Allowed ImmutableSet set2 =  ImmutableSet.of (&quot;1&quot;, &quot;2&quot;, &quot;3&quot;);
ImmutableList An instance of ImmutableList contains its own  data that will never change . List<String> myList = new ArrayList<String>(); myList.add(&quot;first&quot;); myList.add(&quot;second&quot;);
ImmutableList Example List<String> readOnlyList =  Collections.unmodifiableList (myList); readOnlyList.add(&quot;fourth&quot;); //Will throw Exception ImmutableList  list1 = new ImmutableList. Builder ().add(&quot;1&quot;).add(&quot;2&quot;).build(); list1.add(&quot;5&quot;); //Not Allowed List.remove(“1”); //Not Allowed
ImmutableList Example List<String> constList = new ArrayList<String>(); constList.add(&quot;a&quot;); constList.add(&quot;b&quot;); ImmutableList<String> immutableList =  ImmutableList.of (&quot;a&quot;, &quot;b&quot;);
MapDifference An  interface  representing the  differences  between the two given maps.  ImmutableMap<String,Integer> map1 =   new  ImmutableMap.Builder <String,Integer>() .put(&quot;one&quot;, 1).put(&quot;two&quot;, 2).put(&quot;three&quot;, 3).build();  //Above creates an ImmutableMap   // map1  is now {one=1, two=2, three=3}
MapDifference ImmutableMap<String,Integer> map2 = new  ImmutableMap.Builder <String,Integer>() .put(&quot;five&quot;, 5) .put(&quot;four&quot;, 4) .put(&quot;three&quot;, 3) .put(&quot;one&quot;, 10) .build(); // map2  is {five=5, four=4, three=3, one=10}
MapDifference MapDifference <String, Integer> difference =  Maps.difference (map1, map2); difference. entriesInCommon (); difference. entriesDiffering (); difference. entriesOnlyOnLeft (); difference. entriesOnlyOnRight ();
MapDifference difference. areEqual (); MapDifference.ValueDifference <Integer> val = (MapDifference.ValueDifference<Integer>) difference.entriesDiffering(). get (&quot;one&quot;);
Preconditions A final class (com.google.common.base) which provides static methods to verify correct arguments and state. String str = null; Preconditions. checkNotNull( str); int value = -1; Preconditions. checkArgument (value >= 0, &quot;negative value&quot;);
Function Interface A Function (com.google.common.base.Function) is used in transformation of one object to the another. Represented as public interface  Function<F,T>   First argument is the “function input” and second argument is the “function output”.
Function Interface Example Function<String, String>  extractUserName  = new Function<String, String>(){  public String  apply (String emailAddress)  {  String userName = emailAddress.substring(0, emailAddress.indexOf('@'));  return userName;  }  };
Function Example List<String> emailList = Lists.newArrayList(&quot;abc@gmail.com&quot;, &quot;xyz@gmail.com&quot;, &quot;aaa@gmail.com&quot;);  List<String> userNameList = Lists. transform (emailList,  extractUserName );
Function Example Function<String, Integer>  functionStringToInteger  = new Function<String, Integer>(){   public Integer  apply (String str){   return Integer.parseInt(str);   }   };   List strTemp = Lists.newArrayList(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;); List intList = Lists.transform(strTemp,  functionStringToInteger );
Functions Class Function  toStringFunction =  Functions.toStringFunction (); List intList = Lists.newArrayList(1,2,3,4,5); Lists.transform( intList,  toStringFunction );
Predicate A predicate is a way to specify some  conditions  based on an instance of a class The defined predicate then can be used to selectively  filter out  matching instances of that class from a collection.  Predicate<Integer> salaryCut = new  Predicate <Integer>() {   public boolean  apply (Integer salary) {   return salary > 50000;   } };
Predicate Example List<Integer> salaryList = Lists.newArrayList(); salaryList.add(new Integer(20000)); salaryList.add(new Integer(60000)); salaryList.add(new Integer(70000)); salaryList.add(new Integer(40000)); List<Integer> filteredSalary = Lists.newArrayList( Iterables.filter (salaryList,  salaryCut ));
Predicate Example List<String> list1 = Lists.newArrayList(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;); List<String> list2 = Lists.newArrayList(&quot;1&quot;, &quot;4&quot;, &quot;5&quot;); List<String> list3 = Lists.newArrayList(&quot;1&quot;, &quot;4&quot;, &quot;6&quot;); boolean result =  and ( in (list1),in(list2), in(list3)).apply(&quot;4&quot;); result =  or (in(list1),in(list2), in(list3)).apply(&quot;4&quot;);
Predicates ImmutableMap<Integer,String> map = new ImmutableMap.Builder<Integer,String>() .put(10, &quot;Ten&quot;) .put(20, &quot;Twenty&quot;) .put(30, &quot;Thirty&quot;) .build(); Map<Integer,String> filtered11 = Maps.filterKeys (map,Predicates. or ( Predicates. equalTo (10), Predicates. equalTo (30)));
Miscellaneous Joiner  (com.google.common.base) ImmutableSet   s1 =  ImmutableSet.of(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;); String joinedStr  = Joiner.on (&quot;:&quot;). join (s1) ; Joiner joiner = Joiner.on(&quot;* &quot;).skipNulls();   String strWithStar = joiner.join(“A&quot;, null, “B&quot;, “C&quot;);
Joiner joiner = Joiner.on(&quot;* &quot;). useForNull (&quot;Default&quot;);   String str = joiner. join (“A&quot;, null, “B&quot;, “C&quot;); Map<String, String> mp = new LinkedHashMap<String, String>(); mp.put(&quot;1&quot;, &quot;1&quot;); mp.put(&quot;2&quot;, &quot;2&quot;); String str = Joiner.on (&quot;, &quot;). withKeyValueSeparator (&quot;=&quot;).join(mp); //1=1, 2=2
Collections2 Collections2 Predicate<Integer> salaryCut = new  Predicate <Integer>() {   public boolean  apply (Integer salary) {   return salary > 50000;   } };
Collections2 List<Integer> salaryList =  Lists. newArrayList(); salaryList.add(new Integer(20000)); salaryList.add(new Integer(60000)); salaryList.add(new Integer(70000)); salaryList.add(new Integer(40000)); Collection<Integer> newSalaryList =  Collections2.filter (salaryList, salaryCut); newSalaryList.add(1000);//Exception salaryList. clear ();//newSalaryList gets empty too
Maps Static Utility API’s for Java Map. Map<Integer, String> tmpMap = new  HashMap<Integer, String> (); Map<Integer, String> tmpMap1 =  Maps.newHashMap (); //{10=Ten, 20=Twenty, 30=Thirty} Maps. filterKeys (map, Predicates.equalTo(10)); Maps. filterValues (map, Predicates.equalTo(&quot;Ten&quot;));
Map<Integer,String> transformed =  Maps.transformValues (map, new Function<String,String>() { public String apply(String from) { return &quot;A &quot; + from; } }); //10=A Ten, 20=A Twenty, 30=A Thirty}
Lists List<Integer> listA =  Lists.newArrayList (); listA.add(new Integer(1)); listA.add(new Integer(2)); listA.add(new Integer(3)); listA.add(new Integer(4)); listA.add(new Integer(5)); List finalLists =  Lists.partition (listA, 3);
Sets HashSet<String> hSet =  Sets.newHashSet() ; ImmutableSet<String> set1 = ImmutableSet.of(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;); ImmutableSet<String> set2 = ImmutableSet.of(&quot;2&quot;, &quot;3&quot;, &quot;4&quot;); Sets.union (set1, set2); Sets.intersection (set1, set2); Sets.difference (set1, set2); Sets.filter (set1, Predicates.equalTo(&quot;1&quot;))
Where can I refer the API’s? Reference: http://guava-libraries.googlecode.com/svn/trunk/javadoc/index.html http:// code.google.com/p/google -collections/
Thank You!

More Related Content

What's hot (20)

PDF
Stuff you didn't know about action script
Christophe Herreman
 
PPTX
Introduction to Monads in Scala (1)
stasimus
 
PPTX
Java script arrays
Frayosh Wadia
 
PDF
Functions in python
Ilian Iliev
 
PPTX
Collection and framework
SARAVANAN GOPALAKRISHNAN
 
PDF
Swift 함수 커링 사용하기
진성 오
 
PDF
Part 7
acearmin
 
PDF
Composition birds-and-recursion
David Atchley
 
PDF
Hacking parse.y (RubyKansai38)
ujihisa
 
PDF
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
PDF
Java 8 Stream API. A different way to process collections.
David Gómez García
 
DOCX
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
Little Tukta Lita
 
DOC
C - aptitude3
Srikanth
 
PDF
Fp java8
Yanai Franchi
 
PDF
Funkcija, objekt, python
Robert Lujo
 
PDF
Hacking Parse.y with ujihisa
ujihisa
 
PPT
Javascript built in String Functions
Avanitrambadiya
 
PPT
Java Generics for Dummies
knutmork
 
ODP
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
PPT
Javascript arrays
Hassan Dar
 
Stuff you didn't know about action script
Christophe Herreman
 
Introduction to Monads in Scala (1)
stasimus
 
Java script arrays
Frayosh Wadia
 
Functions in python
Ilian Iliev
 
Collection and framework
SARAVANAN GOPALAKRISHNAN
 
Swift 함수 커링 사용하기
진성 오
 
Part 7
acearmin
 
Composition birds-and-recursion
David Atchley
 
Hacking parse.y (RubyKansai38)
ujihisa
 
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
Java 8 Stream API. A different way to process collections.
David Gómez García
 
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
Little Tukta Lita
 
C - aptitude3
Srikanth
 
Fp java8
Yanai Franchi
 
Funkcija, objekt, python
Robert Lujo
 
Hacking Parse.y with ujihisa
ujihisa
 
Javascript built in String Functions
Avanitrambadiya
 
Java Generics for Dummies
knutmork
 
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Javascript arrays
Hassan Dar
 

Viewers also liked (6)

PPT
Ruh i guttya
Sergiyk Kobulyanskuy
 
PPT
масштаб у житті кожного
Sergiyk Kobulyanskuy
 
PPT
Ruh i guttya
Sergiyk Kobulyanskuy
 
PPT
країна чисел
Sergiyk Kobulyanskuy
 
PDF
2008 Fall Roadmap Girls GSKH
Girl Scouts of Kansas Heartland
 
PPTX
багатогранний світ воску
Andrew
 
Ruh i guttya
Sergiyk Kobulyanskuy
 
масштаб у житті кожного
Sergiyk Kobulyanskuy
 
Ruh i guttya
Sergiyk Kobulyanskuy
 
країна чисел
Sergiyk Kobulyanskuy
 
2008 Fall Roadmap Girls GSKH
Girl Scouts of Kansas Heartland
 
багатогранний світ воску
Andrew
 
Ad

Similar to Google collections api an introduction (20)

ODP
Java Boilerplate Busters
HamletDRC
 
ODP
Java Boilerplate Busters
HamletDRC
 
PPTX
Chapter 2
application developer
 
PPT
Php Using Arrays
mussawir20
 
PPTX
JQuery Presentation
Sony Jain
 
PPT
Php Reusing Code And Writing Functions
mussawir20
 
DOCX
WD programs descriptions.docx
anjani pavan kumar
 
ODP
Scala 2 + 2 > 4
Emil Vladev
 
ODP
Scala introduction
Alf Kristian Støyle
 
PPTX
What is new in Java 8
Sandeep Kr. Singh
 
PPTX
Groovy
Zen Urban
 
PPTX
Php-Continuation
lotlot
 
PPTX
Scala en
Fero Kocun
 
PPT
Java 5 Features
sholavanalli
 
ODP
Javascript Unit Testing
Paul Klipp
 
PDF
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
aromanets
 
PPTX
Groovy Api Tutorial
guligala
 
PPTX
C++11 - A Change in Style - v2.0
Yaser Zhian
 
PPT
Whats new in_csharp4
Abed Bukhari
 
Java Boilerplate Busters
HamletDRC
 
Java Boilerplate Busters
HamletDRC
 
Php Using Arrays
mussawir20
 
JQuery Presentation
Sony Jain
 
Php Reusing Code And Writing Functions
mussawir20
 
WD programs descriptions.docx
anjani pavan kumar
 
Scala 2 + 2 > 4
Emil Vladev
 
Scala introduction
Alf Kristian Støyle
 
What is new in Java 8
Sandeep Kr. Singh
 
Groovy
Zen Urban
 
Php-Continuation
lotlot
 
Scala en
Fero Kocun
 
Java 5 Features
sholavanalli
 
Javascript Unit Testing
Paul Klipp
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
aromanets
 
Groovy Api Tutorial
guligala
 
C++11 - A Change in Style - v2.0
Yaser Zhian
 
Whats new in_csharp4
Abed Bukhari
 
Ad

Recently uploaded (20)

PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Python basic programing language for automation
DanialHabibi2
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
July Patch Tuesday
Ivanti
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 

Google collections api an introduction

  • 1. By Jitendra Gosain Google Collections API
  • 2. Introduction What is Google Collections API? Its a utility API. Its an extension to the Java Collections API. Its a set of new Collection Types and implementations. Part of the Project called “ Guava ” Requires “ JDK 1.5”
  • 4. Multimap A collection similar to a Map, but which may associate multiple values with a single key. Keys and values can be null. Adding a new key-value pair equal to an existing key-value pair has no effect.
  • 5. HashMultimap Example HashMultimap<Integer, String> hm = HashMultimap.create (); hm.put(1, &quot;first&quot;);//Add Values to keys hm.put(2, &quot;second&quot;); hm.put(1, &quot;third&quot;); //Same key is added a new value hm.put(1, &quot;fourth&quot;); //hm is {1=[fourth, third, first], 2=[second]}
  • 6. HashMultimap Example hm.remove(1,&quot;first&quot;);//{1=[fourth, third], 2=[second]} hm.removeAll(1);//{2=[second]} Multimap safeMultimap = Multimaps. synchronizedMultimap (hm); SetMultimap safeSetMultimap = Multimaps. synchronizedSetMultimap (hm); Map mp = hm. asMap (); //Converts to Java Map
  • 7. Multiset A Multiset can have duplicates unlike a Java Set. Also called a “ Bag ”. The total number of occurrences of an element in a multiset is called the  count  of that element.
  • 8. HashMultiset Example HashMultiset ms = HashMultiset. create (); ms.add(&quot;1&quot;); ms.add(&quot;2&quot;); ms.add(&quot;1&quot;); ms.add(&quot;3&quot;, 3); //HashMultiset ms is [3 x 3, 2, 1 x 2]
  • 9. HashMultiset Set emSet = ms. elementSet (); //[3, 2, 1] – Above returns set of distinct elements   ms.remove(&quot;1&quot;, 1); //Set is now [3 x 3, 2, 1] ms.remove(&quot;1&quot;, ms.count(&quot;1&quot;)); //[3 x 3, 2] Set set = new HashSet(); set.add(&quot;2&quot;); ms. retainAll (set); //[2] – Retains the elements of Collection “set”
  • 10. BiMap A bimap (or &quot; bidirectional map &quot;) is a map that preserves the uniqueness of its values as well as that of its keys and looking up a key from a value is possible . Also called “ unique-valued map ”. A HashBiMap and its inverse are both serializable.
  • 11. BiMap Example HashBiMap<Integer, String> hmBiMap = HashBiMap. create (); hmBiMap.put(1, &quot;first&quot;); hmBiMap.put(2, &quot;second&quot;); hmBiMap.put(2, “newsecond&quot;); //2 holds this hmBiMap.put(3, &quot;second&quot;); //Above throws an error (value already present)
  • 12. BiMap Example hmBiMap. inverse (); //Above returns the inverse view of this bimap, value mapped to key now. Set set = hmBiMap. values (); //Returns a collection of values of the bimap
  • 13. ImmutableMap An instance of ImmutableMap contains its own data that will never change . Provides read-only access of data. The Java “Collections.unmodifiableMap” which is a  view  of a separate map which can still change, an instance of ImmutableMap contains its own data and will  never  change. Also called the “ Constant Maps ”.
  • 14. ImmutableMap Example ImmutableMap<String,Integer> map1 = new ImmutableMap. Builder <String,Integer>() .put(&quot;one&quot;, 1) .put(&quot;two&quot;, 2) .put(&quot;three&quot;, 3) . build ();//Build an Immutable map
  • 15. ImmutableMap Example map1.put(&quot;four&quot;, 4); //Not allowed map1.remove(4); //Not allowed //Above throws “UnsupportedOperationException” map1. containsKey (&quot;one&quot;); //true map1. containsValue (3); //true
  • 16. ImmutableMap Example Map<String, String> javaMap = new HashMap<String, String>(); javaMap.put(&quot;key1&quot;, &quot;value1&quot;); javaMap.put(&quot;key2&quot;, &quot;value2&quot;); ImmutableMap<String,String> map = ImmutableMap.of (&quot;key1&quot;, &quot;value1&quot;, &quot;key2&quot;, &quot;value2&quot;);
  • 17. ImmutableSet An instance of the ImmutableSet contains its own data that will not change . ImmutableSet set1 = new ImmutableSet. Builder ().add(&quot;1&quot;).add(&quot;2&quot;) .build(); set1.add(“3”); //Its not Allowed set1.remove(“1”); //Not Allowed ImmutableSet set2 = ImmutableSet.of (&quot;1&quot;, &quot;2&quot;, &quot;3&quot;);
  • 18. ImmutableList An instance of ImmutableList contains its own data that will never change . List<String> myList = new ArrayList<String>(); myList.add(&quot;first&quot;); myList.add(&quot;second&quot;);
  • 19. ImmutableList Example List<String> readOnlyList = Collections.unmodifiableList (myList); readOnlyList.add(&quot;fourth&quot;); //Will throw Exception ImmutableList list1 = new ImmutableList. Builder ().add(&quot;1&quot;).add(&quot;2&quot;).build(); list1.add(&quot;5&quot;); //Not Allowed List.remove(“1”); //Not Allowed
  • 20. ImmutableList Example List<String> constList = new ArrayList<String>(); constList.add(&quot;a&quot;); constList.add(&quot;b&quot;); ImmutableList<String> immutableList = ImmutableList.of (&quot;a&quot;, &quot;b&quot;);
  • 21. MapDifference An interface representing the differences between the two given maps. ImmutableMap<String,Integer> map1 = new ImmutableMap.Builder <String,Integer>() .put(&quot;one&quot;, 1).put(&quot;two&quot;, 2).put(&quot;three&quot;, 3).build(); //Above creates an ImmutableMap // map1 is now {one=1, two=2, three=3}
  • 22. MapDifference ImmutableMap<String,Integer> map2 = new ImmutableMap.Builder <String,Integer>() .put(&quot;five&quot;, 5) .put(&quot;four&quot;, 4) .put(&quot;three&quot;, 3) .put(&quot;one&quot;, 10) .build(); // map2 is {five=5, four=4, three=3, one=10}
  • 23. MapDifference MapDifference <String, Integer> difference = Maps.difference (map1, map2); difference. entriesInCommon (); difference. entriesDiffering (); difference. entriesOnlyOnLeft (); difference. entriesOnlyOnRight ();
  • 24. MapDifference difference. areEqual (); MapDifference.ValueDifference <Integer> val = (MapDifference.ValueDifference<Integer>) difference.entriesDiffering(). get (&quot;one&quot;);
  • 25. Preconditions A final class (com.google.common.base) which provides static methods to verify correct arguments and state. String str = null; Preconditions. checkNotNull( str); int value = -1; Preconditions. checkArgument (value >= 0, &quot;negative value&quot;);
  • 26. Function Interface A Function (com.google.common.base.Function) is used in transformation of one object to the another. Represented as public interface Function<F,T> First argument is the “function input” and second argument is the “function output”.
  • 27. Function Interface Example Function<String, String> extractUserName = new Function<String, String>(){ public String apply (String emailAddress) { String userName = emailAddress.substring(0, emailAddress.indexOf('@')); return userName; } };
  • 28. Function Example List<String> emailList = Lists.newArrayList(&quot;[email protected]&quot;, &quot;[email protected]&quot;, &quot;[email protected]&quot;); List<String> userNameList = Lists. transform (emailList, extractUserName );
  • 29. Function Example Function<String, Integer> functionStringToInteger = new Function<String, Integer>(){ public Integer apply (String str){ return Integer.parseInt(str); } }; List strTemp = Lists.newArrayList(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;); List intList = Lists.transform(strTemp, functionStringToInteger );
  • 30. Functions Class Function toStringFunction = Functions.toStringFunction (); List intList = Lists.newArrayList(1,2,3,4,5); Lists.transform( intList, toStringFunction );
  • 31. Predicate A predicate is a way to specify some conditions based on an instance of a class The defined predicate then can be used to selectively filter out matching instances of that class from a collection. Predicate<Integer> salaryCut = new Predicate <Integer>() { public boolean apply (Integer salary) { return salary > 50000; } };
  • 32. Predicate Example List<Integer> salaryList = Lists.newArrayList(); salaryList.add(new Integer(20000)); salaryList.add(new Integer(60000)); salaryList.add(new Integer(70000)); salaryList.add(new Integer(40000)); List<Integer> filteredSalary = Lists.newArrayList( Iterables.filter (salaryList, salaryCut ));
  • 33. Predicate Example List<String> list1 = Lists.newArrayList(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;); List<String> list2 = Lists.newArrayList(&quot;1&quot;, &quot;4&quot;, &quot;5&quot;); List<String> list3 = Lists.newArrayList(&quot;1&quot;, &quot;4&quot;, &quot;6&quot;); boolean result = and ( in (list1),in(list2), in(list3)).apply(&quot;4&quot;); result = or (in(list1),in(list2), in(list3)).apply(&quot;4&quot;);
  • 34. Predicates ImmutableMap<Integer,String> map = new ImmutableMap.Builder<Integer,String>() .put(10, &quot;Ten&quot;) .put(20, &quot;Twenty&quot;) .put(30, &quot;Thirty&quot;) .build(); Map<Integer,String> filtered11 = Maps.filterKeys (map,Predicates. or ( Predicates. equalTo (10), Predicates. equalTo (30)));
  • 35. Miscellaneous Joiner (com.google.common.base) ImmutableSet s1 = ImmutableSet.of(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;); String joinedStr = Joiner.on (&quot;:&quot;). join (s1) ; Joiner joiner = Joiner.on(&quot;* &quot;).skipNulls(); String strWithStar = joiner.join(“A&quot;, null, “B&quot;, “C&quot;);
  • 36. Joiner joiner = Joiner.on(&quot;* &quot;). useForNull (&quot;Default&quot;); String str = joiner. join (“A&quot;, null, “B&quot;, “C&quot;); Map<String, String> mp = new LinkedHashMap<String, String>(); mp.put(&quot;1&quot;, &quot;1&quot;); mp.put(&quot;2&quot;, &quot;2&quot;); String str = Joiner.on (&quot;, &quot;). withKeyValueSeparator (&quot;=&quot;).join(mp); //1=1, 2=2
  • 37. Collections2 Collections2 Predicate<Integer> salaryCut = new Predicate <Integer>() { public boolean apply (Integer salary) { return salary > 50000; } };
  • 38. Collections2 List<Integer> salaryList = Lists. newArrayList(); salaryList.add(new Integer(20000)); salaryList.add(new Integer(60000)); salaryList.add(new Integer(70000)); salaryList.add(new Integer(40000)); Collection<Integer> newSalaryList = Collections2.filter (salaryList, salaryCut); newSalaryList.add(1000);//Exception salaryList. clear ();//newSalaryList gets empty too
  • 39. Maps Static Utility API’s for Java Map. Map<Integer, String> tmpMap = new HashMap<Integer, String> (); Map<Integer, String> tmpMap1 = Maps.newHashMap (); //{10=Ten, 20=Twenty, 30=Thirty} Maps. filterKeys (map, Predicates.equalTo(10)); Maps. filterValues (map, Predicates.equalTo(&quot;Ten&quot;));
  • 40. Map<Integer,String> transformed = Maps.transformValues (map, new Function<String,String>() { public String apply(String from) { return &quot;A &quot; + from; } }); //10=A Ten, 20=A Twenty, 30=A Thirty}
  • 41. Lists List<Integer> listA = Lists.newArrayList (); listA.add(new Integer(1)); listA.add(new Integer(2)); listA.add(new Integer(3)); listA.add(new Integer(4)); listA.add(new Integer(5)); List finalLists = Lists.partition (listA, 3);
  • 42. Sets HashSet<String> hSet = Sets.newHashSet() ; ImmutableSet<String> set1 = ImmutableSet.of(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;); ImmutableSet<String> set2 = ImmutableSet.of(&quot;2&quot;, &quot;3&quot;, &quot;4&quot;); Sets.union (set1, set2); Sets.intersection (set1, set2); Sets.difference (set1, set2); Sets.filter (set1, Predicates.equalTo(&quot;1&quot;))
  • 43. Where can I refer the API’s? Reference: http://guava-libraries.googlecode.com/svn/trunk/javadoc/index.html http:// code.google.com/p/google -collections/

Editor's Notes

  • #27: Make sure every machine has JBoss installed
  • #28: Make sure everyone has this done on their local JBoss install