Top Banner
1 By Jitendra Gosain Google Collections API
44

Google collections api an introduction

May 18, 2015

Download

Technology

gosain20

Google Collections API
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Google collections api   an introduction

1

By Jitendra Gosain

Google Collections API

Page 2: Google collections api   an introduction

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”

Demo
Page 3: Google collections api   an introduction

3

Key Interfaces and Classes

Page 4: Google collections api   an introduction

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.

Page 5: Google collections api   an introduction

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]}

Page 6: Google collections api   an introduction

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

Page 7: Google collections api   an introduction

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.

Page 8: Google collections api   an introduction

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]

Page 9: Google collections api   an introduction

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”

Page 10: Google collections api   an introduction

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.

Page 11: Google collections api   an introduction

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)

Page 12: Google collections api   an introduction

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

Page 13: Google collections api   an introduction

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”.

Page 14: Google collections api   an introduction

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

Page 15: Google collections api   an introduction

15

ImmutableMap Examplemap1.put("four", 4); //Not allowedmap1.remove(4); //Not allowed//Above throws “UnsupportedOperationException”

map1.containsKey("one"); //truemap1.containsValue(3); //true

Page 16: Google collections api   an introduction

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

Page 17: Google collections api   an introduction

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

Page 18: Google collections api   an introduction

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

Page 19: Google collections api   an introduction

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

Page 20: Google collections api   an introduction

20

ImmutableList Example

List<String> constList = new ArrayList<String>();

constList.add("a");

constList.add("b");

ImmutableList<String> immutableList = ImmutableList.of("a", "b");

Page 21: Google collections api   an introduction

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}

Page 22: Google collections api   an introduction

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}

Page 23: Google collections api   an introduction

23

MapDifferenceMapDifference<String, Integer> difference =

Maps.difference(map1, map2);

difference.entriesInCommon();

difference.entriesDiffering();

difference.entriesOnlyOnLeft();

difference.entriesOnlyOnRight();

Page 24: Google collections api   an introduction

24

MapDifference

difference.areEqual();

MapDifference.ValueDifference<Integer> val = (MapDifference.ValueDifference<Integer>) difference.entriesDiffering().get("one");

Page 25: Google collections api   an introduction

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

Page 26: Google collections api   an introduction

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”.

Page 27: Google collections api   an introduction

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;

} };

Page 28: Google collections api   an introduction

28

Function Example

List<String> emailList = Lists.newArrayList("[email protected]", "[email protected]", "[email protected]");

List<String> userNameList = Lists.transform(emailList, extractUserName);

Page 29: Google collections api   an introduction

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

Page 30: Google collections api   an introduction

30

Functions Class

Function toStringFunction = Functions.toStringFunction();

List intList = Lists.newArrayList(1,2,3,4,5);

Lists.transform(intList, toStringFunction);

Page 31: Google collections api   an introduction

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

Page 32: Google collections api   an introduction

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

Page 33: Google collections api   an introduction

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

Page 34: Google collections api   an introduction

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

Page 35: Google collections api   an introduction

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

Page 36: Google collections api   an introduction

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

Page 37: Google collections api   an introduction

37

Collections2

Collections2

Predicate<Integer> salaryCut = new Predicate<Integer>() {

public boolean apply(Integer salary) {

return salary > 50000;

}

};

Page 38: Google collections api   an introduction

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

Page 39: Google collections api   an introduction

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

Page 40: Google collections api   an introduction

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}

Page 41: Google collections api   an introduction

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

Page 42: Google collections api   an introduction

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"))

Page 43: Google collections api   an introduction

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/

Page 44: Google collections api   an introduction

44

Thank You!