Post on 18-May-2015
description
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”
3
Key Interfaces and Classes
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 ExampleHashMultimap<Integer, String> hm =
HashMultimap.create();
hm.put(1, "first");//Add Values to keys
hm.put(2, "second");
hm.put(1, "third"); //Same key is added a new value
hm.put(1, "fourth");
//hm is {1=[fourth, third, first], 2=[second]}
6
HashMultimap Example
hm.remove(1,"first");//{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("1"); ms.add("2"); ms.add("1");
ms.add("3", 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("1", 1); //Set is now [3 x 3, 2, 1]ms.remove("1", ms.count("1")); //[3 x 3, 2]Set set = new HashSet();set.add("2");ms.retainAll(set);//[2] – Retains the elements of Collection “set”
10
BiMap A bimap (or "bidirectional map") 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 ExampleHashBiMap<Integer, String> hmBiMap = HashBiMap.create();
hmBiMap.put(1, "first"); hmBiMap.put(2, "second");
hmBiMap.put(2, “newsecond"); //2 holds this
hmBiMap.put(3, "second"); //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("one", 1) .put("two", 2) .put("three", 3) .build();//Build an Immutable map
15
ImmutableMap Examplemap1.put("four", 4); //Not allowedmap1.remove(4); //Not allowed//Above throws “UnsupportedOperationException”
map1.containsKey("one"); //truemap1.containsValue(3); //true
16
ImmutableMap Example
Map<String, String> javaMap = new HashMap<String, String>();
javaMap.put("key1", "value1");
javaMap.put("key2", "value2");
ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");
17
ImmutableSet An instance of the ImmutableSet contains its own
data that will not change.
ImmutableSet set1 = new ImmutableSet.Builder().add("1").add("2") .build();
set1.add(“3”); //Its not Allowed
set1.remove(“1”); //Not Allowed
ImmutableSet set2 = ImmutableSet.of("1", "2", "3");
18
ImmutableList
An instance of ImmutableList contains its own data that will never change.
List<String> myList = new ArrayList<String>();
myList.add("first");
myList.add("second");
19
ImmutableList Example
List<String> readOnlyList = Collections.unmodifiableList(myList);
readOnlyList.add("fourth"); //Will throw ExceptionImmutableList list1 = new
ImmutableList.Builder().add("1").add("2").build();
list1.add("5"); //Not AllowedList.remove(“1”); //Not Allowed
20
ImmutableList Example
List<String> constList = new ArrayList<String>();
constList.add("a");
constList.add("b");
ImmutableList<String> immutableList = ImmutableList.of("a", "b");
21
MapDifference An interface representing the differences
between the two given maps.
ImmutableMap<String,Integer> map1 =
new ImmutableMap.Builder<String,Integer>()
.put("one", 1).put("two", 2).put("three", 3).build();
//Above creates an ImmutableMap
//map1 is now {one=1, two=2, three=3}
22
MapDifferenceImmutableMap<String,Integer> map2 =
new ImmutableMap.Builder<String,Integer>().put("five", 5).put("four", 4).put("three", 3).put("one", 10).build();//map2 is {five=5, four=4, three=3, one=10}
23
MapDifferenceMapDifference<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("one");
25
PreconditionsA 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, "negative value");
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 ExampleFunction<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("abc@gmail.com", "xyz@gmail.com", "aaa@gmail.com");
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("1", "2", "3", "4");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 ExampleList<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 ExampleList<String> list1 = Lists.newArrayList("1", "2", "3");List<String> list2 = Lists.newArrayList("1", "4", "5");List<String> list3 = Lists.newArrayList("1", "4", "6");boolean result = and(in(list1),in(list2),
in(list3)).apply("4");result = or(in(list1),in(list2), in(list3)).apply("4");
34
PredicatesImmutableMap<Integer,String> map = new
ImmutableMap.Builder<Integer,String>()
.put(10, "Ten")
.put(20, "Twenty")
.put(30, "Thirty") .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("1", "2", "3");
String joinedStr = Joiner.on(":").join(s1);
Joiner joiner = Joiner.on("* ").skipNulls();
String strWithStar = joiner.join(“A", null, “B", “C");
36
Joinerjoiner = Joiner.on("* ").useForNull("Default"); String str = joiner.join(“A", null, “B", “C");Map<String, String> mp = new
LinkedHashMap<String, String>();mp.put("1", "1"); mp.put("2", "2");
String str = Joiner.on(", ").withKeyValueSeparator("=").join(mp);
//1=1, 2=2
37
Collections2
Collections2
Predicate<Integer> salaryCut = new Predicate<Integer>() {
public boolean apply(Integer salary) {
return salary > 50000;
}
};
38
Collections2List<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);//ExceptionsalaryList.clear();//newSalaryList gets empty too
39
MapsStatic 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("Ten"));
40
Map<Integer,String> transformed = Maps.transformValues(map, new Function<String,String>() {
public String apply(String from) {
return "A " + 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
SetsHashSet<String> hSet = Sets.newHashSet();
ImmutableSet<String> set1 = ImmutableSet.of("1", "2", "3");
ImmutableSet<String> set2 = ImmutableSet.of("2", "3", "4");
Sets.union(set1, set2);
Sets.intersection(set1, set2);
Sets.difference(set1, set2);
Sets.filter(set1, Predicates.equalTo("1"))
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/
44
Thank You!