The largest Interview Solution Library on the web


« Previous | 1 | 2 | 3 | Next »

Guava - COLLECTIONS UTILITIES


Guava introduces many advanced collections based on developers' experience in application development works. Given below is a list of useful collections:
S.N.Collection name & Description
1Multiset
An extension to Set interface to allow duplicate elements.
2Multimap
An extension to Map interface so that its keys can be mapped to multiple values at a time.
3BiMap
An extension to Map interface to support inverse operations.
4Table
Table represents a special map where two keys can be specified in combined fashion to refer to a single value.
Multiset Interfacet

Multiset interface extends ‘Set’ to have duplicate elements, and provides various utility methods to deal with the occurrences of such elements in a set.

Interface Declaration

Following is the declaration for com.google.common.collect.Multiset<E> interface:
@GwtCompatible
public interface Multiset<E>
extends Collection<E>

Interface Methods
S.N.Method & Description
1boolean add(E element)
Adds a single occurrence of the specified element to this multiset.
2int add(E element, int occurrences)
Adds a number of occurrences of an element to this multiset.
3boolean contains(Object element)
Determines whether this multiset contains the specified element.
4boolean containsAll(Collection<?> elements)
Returns true if this multiset contains at least one occurrence of each element in the specified collection.
5int count(Object element)
Returns the number of occurrences of an element in this multiset (the count of the element).
6Set<E> elementSet()
Returns the set of distinct elements contained in this multiset.
7Set<Multiset.Entry<E>> entrySet()
Returns a view of the contents of this multiset, grouped into Multiset.Entry instances, each providing an element of the multiset and the count of that element.
8boolean equals(Object object)
Compares the specified object with this multiset for equality.
9int hashCode()
Returns the hash code for this multiset.
10Iterator<E> iterator()
Returns an iterator over the elements in this collection.
11boolean remove(Object element)
Removes a single occurrence of the specified element from this multiset, if present.
12int remove(Object element, int occurrences)
Removes a number of occurrences of the specified element from this multiset.
13boolean removeAll(Collection<?> c)
Removes all of this collection's elements that are also contained in the specified collection (optional operation).
14boolean retainAll(Collection<?> c)
Retains only the elements in this collection that are contained in the specified collection (optional operation).
15int setCount(E element, int count)
Adds or removes the necessary occurrences of an element such that the element attains the desired count.
16boolean setCount(E element, int oldCount, int newCount)
Conditionally sets the count of an element to a new value, as described in setCount(Object, int), provided that the element has the expected current count.
17String toString()
Returns a string representation of the object.
Methods Inherited

This interface inherits methods from the following interface:
  • java.util.Collection
Example of Multiset

Create the following java program using any editor of your choice in say C:/> Guava.

GuavaTester.java

import java.util.Iterator;
import java.util.Set;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
public class GuavaTester {
public static void main(String args[]){
//create a multiset collection
Multiset<String> multiset = HashMultiset.create();
multiset.add("a");
multiset.add("b");
multiset.add("c");
multiset.add("d");
multiset.add("a");
multiset.add("b");
multiset.add("c");
multiset.add("b");
multiset.add("b");
multiset.add("b");
//print the occurrence of an element
System.out.println("Occurrence of 'b' : "+multiset.count("b"));
//print the total size of the multiset
System.out.println("Total Size : "+multiset.size());
//get the distinct elements of the multiset as set
Set<String> set = multiset.elementSet();
//display the elements of the set
System.out.println("Set [");
for (String s : set) {
System.out.println(s);
}
System.out.println("]");
//display all the elements of the multiset using iterator
Iterator<String> iterator = multiset.iterator();
System.out.println("MultiSet [");
while(iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("]");
//display the distinct elements of the multiset with their occurrence count
System.out.println("MultiSet [");
for (Multiset.Entry<String> entry : multiset.entrySet())
{
System.out.println("Element: "+entry.getElement() +", Occurrence(s): " + entry.getCount());
}
System.out.println("]");
//remove extra occurrences
multiset.remove("b",2);
//print the occurrence of an element
System.out.println("Occurence of 'b' : "+multiset.count("b"));
}
}

Verify the Result

Compile the class using javac compiler as follows:

C:\Guava>javac GuavaTester.java

Now run the GuavaTester to see the result.

C:\Guava>java GuavaTester

See the result.

Occurence of 'b' : 5
Total Size : 10
Set [
d
b
c
a
]
MultiSet [
d
b
b
b
b
b
c
c
a
a
]
MultiSet [
Element: d, Occurence(s): 1
Element: b, Occurence(s): 5
Element: c, Occurence(s): 2
Element: a, Occurence(s): 2
]
Occurence of 'b' : 3

Multimap Interface

Multimap interface extends Map so that its keys can be mapped to multiple values at a time.

Interface Interface Interface Interface Interface Interface Interface Interface Interface

Interface Declaration

Following is the declaration for com.google.common.collect.Multimap<K,V> interface:

@GwtCompatible
public interface Multimap<K,V>

Interface Methods
S.N.Method & Description
1Map<K,Collection<V>> asMap()
Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key's associated values.
2void clear()
Removes all key-value pairs from the multimap, leaving it empty.
3boolean containsEntry(Object key, Object value)
Returns true if this multimap contains at least one key-value pair with the key and the value.
4boolean containsKey(Object key)
Returns true if this multimap contains at least one key-value pair with the key.
5boolean containsValue(Object value)
Returns true if this multimap contains at least one key-value pair with the value.
6Collection<Map.Entry<K,V>> entries()
Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances.
7boolean equals(Object obj)
Compares the specified object with this multimap for equality.
8Collection<V> get(K key)
Returns a view collection of the values associated with key in this multimap, if any.
9int hashCode()
Returns the hash code for this multimap.
10boolean isEmpty()
Returns true if this multimap contains no key-value pairs.
11Multiset<K> keys()
Returns a view collection containing the key from each key-value pair in this multimap, without collapsing duplicates.
12Set<K> keySet()
Returns a view collection of all distinct keys contained in this multimap.
13boolean put(K key, V value)
Stores a key-value pair in this multimap.
14boolean putAll(K key, Iterable<? extends V> values)
Stores a key-value pair in this multimap for each of values, all using the same key, key.
15boolean putAll(Multimap<? extends K,? extends V> multimap)
Stores all key-value pairs of multimap in this multimap, in the order returned by multimap.entries().
16boolean remove(Object key, Object value)
Removes a single key-value pair with the key and the value from this multimap, if such exists.
17Collection<V> removeAll(Object key)
Removes all values associated with the key.
18Collection<V> replaceValues(K key, Iterable<? extends V> values)
Stores a collection of values with the same key, replacing any existing values for that key.
19int size()
Returns the number of key-value pairs in this multimap.
20Returns a view collection containing the value from each key-value pair contained in this multimap, without collapsing duplicates (so values().size() == size()).
Returns a view collection containing the value from each key-value pair contained in this multimap, without collapsing duplicates (so values().size() == size()).
Example of Multimap

Create the following java program using any editor of your choice in say C:/> Guava.

GuavaTester.java
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class GuavaTester {
public static void main(String args[]){
GuavaTester tester = new GuavaTester();
Multimap<String,String> multimap = tester.getMultimap();
List<String> lowerList = (List<String>)multimap.get("lower");
System.out.println("Initial lower case list");
System.out.println(lowerList.toString());
lowerList.add("f");
System.out.println("Modified lower case list");
System.out.println(lowerList.toString());
List<String> upperList = (List<String>)multimap.get("upper");
System.out.println("Initial upper case list");
System.out.println(upperList.toString());
upperList.remove("D");
System.out.println("Modified upper case list");
System.out.println(upperList.toString());
Map<String, Collection<String>> map = multimap.asMap();
System.out.println("Multimap as a map");
for (Map.Entry<String, Collection<String>> entry : map.entrySet())
{
String key = entry.getKey();
Collection<String> value = multimap.get("lower");
System.out.println(key + ":" + value);
}
System.out.println("Keys of Multimap");
Set<String> keys = multimap.keySet();
for(String key:keys){
System.out.println(key);
}
System.out.println("Values of Multimap");
Collection<String> values = multimap.values();
System.out.println(values);
}
private Multimap<String,String> getMultimap(){
//Map<String, List<String>>
// lower -> a, b, c, d, e
// upper -> A, B, C, D
Multimap<String,String> multimap = ArrayListMultimap.create();
multimap.put("lower", "a");
multimap.put("lower", "b");
multimap.put("lower", "c");
multimap.put("lower", "d");
multimap.put("lower", "e");
multimap.put("upper", "A");
multimap.put("upper", "B");
multimap.put("upper", "C");
multimap.put("upper", "D");
return multimap;
} }

Verify the Result

Compile the class using javac compiler as follows:

C:\Guava>javac GuavaTester.java

Now run the GuavaTester to see the result.

C:\Guava>java GuavaTester

See the result.

Initial lower case list
[a, b, c, d, e]
Modified lower case list
[a, b, c, d, e, f]
Initial upper case list
[A, B, C, D]
Modified upper case list
[A, B, C]
Multimap as a map
upper:[a, b, c, d, e, f]
lower:[a, b, c, d, e, f]
Keys of Multimap
upper
lower
Values of Multimap
[A, B, C, a, b, c, d, e, f]

Bi Map Interface

A BiMap is a special kind of map which maintains an inverse view of the map while ensuring that no duplicate values are present in the map and a value can be used safely to get the key back.

Interface Interface Interface Interface Interface Interface Interface Interface Interface

Interface Declaration

Following is the declaration for com.google.common.collect.Bimap<K,V> interface:

@GwtCompatible
public interface BiMap<K,V>
extends Map<K,V>

S.N.Method & Description
1V forcePut(K key, V value)
An alternate form of ‘put’ that silently removes any existing entry with the value before proceeding with the put(K, V) operation.
2BiMap<V,K> inverse()
Returns the inverse view of this bimap, which maps each of this bimap's values to its associated key.
3V put(K key, V value)
Associates the specified value with the specified key in this map (optional operation).
4void putAll(Map<? extends K,? extends V> map)
Copies all of the mappings from the specified map to this map (optional operation).
5Set<V> values()
Returns a Collection view of the values contained in this map.
Methods Inherited

This class inherits methods from the following interface:
  • java.util.Map
Example of BiMap

Create the following java program using any editor of your choice in say C:/> Guava.

GuavaTester.java
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
public class GuavaTester {
public static void main(String args[]){
BiMap<Integer, String> empIDNameMap = HashBiMap.create();
empIDNameMap.put(new Integer(101), "Mahesh");
empIDNameMap.put(new Integer(102), "Sohan");
empIDNameMap.put(new Integer(103), "Ramesh");
//Emp Id of Employee "Mahesh"
System.out.println(empIDNameMap.inverse().get("Mahesh"));
}
}

Verify the Result

Compile the class using javac compiler as follows:

C:\Guava>javac GuavaTester.java

Now run the GuavaTester to see the result.

C:\Guava>java GuavaTester

See the result.

101

Table Interface

Table represents a special map where two keys can be specified in combined fashion to refer to a single value. It is similar to creating a map of maps.

Interface Declaration

Following is the declaration for com.google.common.collect.Table<R,C,V> interface:

@GwtCompatible
public interface Table<R,C,V>

Interface Methods
S.N.Method & Description
1Set<Table.Cell<R,C,V>> cellSet()
Returns a set of all row key/column key/value triplets.
2void clear()
Removes all mappings from the table.
3Map<R,V> column(C columnKey)
Returns a view of all mappings that have the given column key.
4Set<C> columnKeySet()
Returns a set of column keys that have one or more values in the table.
5Map<C,Map<R,V>> columnMap()
Returns a view that associates each column key with the corresponding map from row keys to values.
6boolean contains(Object rowKey, Object columnKey)
Returns true if the table contains a mapping with the specified row and column keys.
7boolean containsColumn(Object columnKey)
Returns true if the table contains a mapping with the specified column.
8boolean containsRow(Object rowKey)
Returns true if the table contains a mapping with the specified row key.
9boolean containsValue(Object value)
Returns true if the table contains a mapping with the specified value.
10boolean equals(Object obj)
Compares the specified object with this table for equality.
11V get(Object rowKey, Object columnKey)
Returns the value corresponding to the given row and column keys, or null if no such mapping exists.
12int hashCode()
Returns the hash code for this table.
13boolean isEmpty()
Returns true if the table contains no mappings.
14V put(R rowKey, C columnKey, V value)
Associates the specified value with the specified keys.
15void putAll(Table<? extends R,? extends C,? extends V> table)
Copies all mappings from the specified table to this table.
16V remove(Object rowKey, Object columnKey)
Removes the mapping, if any, associated with the given keys.
17Map<C,V> row(R rowKey)
Returns a view of all mappings that have the given row key.
18Set<R> rowKeySet()
Returns a set of row keys that have one or more values in the table.
19Map<R,Map<C,V>> rowMap()
Returns a view that associates each row key with the corresponding map from column keys to values.
20int size()
Returns the number of row key / column key / value mappings in the table.
21Collection<V> values()
Returns a collection of all values, which may contain duplicates.
Example of Table Interface

Create the following java program using any editor of your choice in say C:/> Guava.

GuavaTester.java
import java.util.Map;
import java.util.Set;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
public class GuavaTester {
public static void main(String args[]){
//Table<R,C,V> == Map<R,Map<C,V>>
/*
* Company: IBM, Microsoft, TCS
* IBM -> {101:Mahesh, 102:Ramesh, 103:Suresh}
* Microsoft -> {101:Sohan, 102:Mohan, 103:Rohan }
* TCS -> {101:Ram, 102: Shyam, 103: Sunil }
*
* */
//create a table
Table<String, String, String> employeeTable =
HashBasedTable.create();
//initialize the table with employee details
employeeTable.put("IBM", "101","Mahesh");
employeeTable.put("IBM", "102","Ramesh");
employeeTable.put("IBM", "103","Suresh");
employeeTable.put("Microsoft", "111","Sohan");
employeeTable.put("Microsoft", "112","Mohan");
employeeTable.put("Microsoft", "113","Rohan");
employeeTable.put("TCS", "121","Ram");
employeeTable.put("TCS", "122","Shyam");
employeeTable.put("TCS", "123","Sunil");
//get Map corresponding to IBM
Map<String,String> ibmEmployees = employeeTable.row("IBM");
System.out.println("List of IBM Employees");
for(Map.Entry<String, String> entry : ibmEmployees.entrySet()){
System.out.println("Emp Id: " + entry.getKey() + ", Name: " +
entry.getValue());
}
//get all the unique keys of the table
Set<String> employers = employeeTable.rowKeySet();
System.out.print("Employers: ");
for(String employer: employers){
System.out.print(employer + " ");
}
System.out.println();
//get a Map corresponding to 102
Map<String,String> EmployerMap = employeeTable.column("102");
for(Map.Entry<String, String> entry : EmployerMap.entrySet()){
System.out.println("Employer: " + entry.getKey() + ", Name: " +
entry.getValue());
}
}
}

Verify the Result

Compile the class using javac compiler as follows:

C:\Guava>javac GuavaTester.java

Now run the GuavaTester to see the result.

C:\Guava>java GuavaTester

See the result.

List of IBM Employees
Emp Id: 102, Name: Ramesh
Emp Id: 101, Name: Mahesh
Emp Id: 103, Name: Suresh
Employers: IBM TCS Microsoft
Employer: IBM, Name: Ramesh
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com