Google Collections – An Overview with sample tutorials

One of the most commonly or widely used data structures within the Java language are the Collections. However time and again developers have felt the need for more flexibility leading to the Apache Commons Collection library and now the Google Collections library.

There is already an article devoted to comparing the two libraries and I do not intend to take sides here. In this post I just intend to prepare certain easy-to-use reference examples for using the Google Collections library.

First stop Preconditions. A common requirement during software development or implementation of an API is to confirm if the argument provided by the callee is null or blank. Let’s take a typical example using the Person class.

package com.vinraj.preconditions;

public class Person {

    private String firstName = null;
    private String lastName = null;

    public Person(String firstName, String lastName) {
	this.firstName = firstName;
	this.lastName = lastName;

    }

    public String getName() {
	if (this.firstName == null || this.lastName == null) {
	    throw new NullPointerException("First/Last name " +
	    "of the person cannot be null.");
	}
	    return this.firstName + " " + this.lastName;
    }

}

We need to validate if either the first or the last name is null. Under normal circumstances the getName method implementation would be on the lines shown above. Let’s develop a small test program

package com.vinraj.preconditions;

public class PersonTest {

    public static void main(String[] args) {
	Person p = new Person("Bill", null);
	System.out.println(p.getName());
    }

}

Running the test program generates the following ouput:

Exception in thread "main" java.lang.NullPointerException:
First/Last name of the person cannot be null.
at com.vinraj.preconditions.Person.getName(Person.java:19)
at com.vinraj.preconditions.PersonTest.main(PersonTest.java:7)

But with Google Collections in the picture the implementation of getName method is changed to as below.

    public String getName() {

	Preconditions.checkArgument(this.firstName != null
	     && this.lastName != null,
	    "First/Last name of the person cannot be null.");
	return this.firstName + " " + this.lastName;

    }

We run the same test program and see the following result:

Exception in thread "main" java.lang.IllegalArgumentException:
First/Last name of the person cannot be null.
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:85)
at com.vinraj.preconditions.Person.getName(Person.java:25)
at com.vinraj.preconditions.PersonTest.main(PersonTest.java:7)

We can also use an overloaded checkArgument method for adding a bit more niceties.

public String getName() {
    Preconditions.checkArgument(this.firstName != null && this.lastName != null,
	"%s or %s of the person cannot be null.", "First Name", "Last Name");
    return this.firstName + " " + this.lastName;
}

Additionally the Preconditions has another method called checkState to validate boolean statuses. Null references conditions can be checked using the checkNotNull methods.

One interesting method provided with the Preconditions class is checkContentsNotNull. Sometimes we need to check if a collection has any null objects. Here’s a sample implementation.

package com.vinraj.preconditions;

import java.util.ArrayList;
import java.util.List;

import com.google.common.base.Preconditions;

public class PersonListTest {

    public static void main(String[] args) {
	List<Person> persons = new ArrayList<Person>();
	persons.add(null);
	Preconditions.checkContentsNotNull(persons);

    }

}

On running the program the following output is displayed on the console.

Exception in thread "main" java.lang.NullPointerException
at com.google.common.base.Preconditions.
    checkNotNull(Preconditions.java:171)
at com.google.common.base.Preconditions.
    checkContentsNotNull(Preconditions.java:227)
at com.vinraj.preconditions.PersonListTest.
   main(PersonListTest.java:13)

Let’s look at the next Google Collections class Iterables. The Iterables class provides a method named getOnlyElement. The method returns the object in the collection container provided the collection size is 1. If the size is more than one, an IllegalArgumentException is thrown.

Here’s a sample program for verifying the above.

package com.vinraj.iterable;

import java.util.ArrayList;
import java.util.List;

import com.google.common.collect.Iterables;

public class IterableTest {

    public static void main(String[] args) {
	List<Integer> container = new ArrayList<Integer>();
	container.add(Integer.valueOf(1));
	container.add(Integer.valueOf(2));
	System.out.println(Iterables.getOnlyElement(container));

    }
}

The output generated on the console is:

Exception in thread "main" java.lang.IllegalArgumentException:
    extra elements found: [2]
at com.google.common.collect.Iterators.
    getOnlyElement(Iterators.java:116)
at com.google.common.collect.Iterables.
    getOnlyElement(Iterables.java:92)
at com.vinraj.iterable.IterableTest.main(IterableTest.java:14)

The getOnlyElement method is overloaded with a method accepting two parameters. Its behaviour is similar to the implementation described above except that if the collection has no elements it returns the default value passed as second argument to the method.

The Iterables provides a very useful utility method named elementsEqual. It compares two Iterable objects and determines if the two hold the same objects. Here’s a sample program to explain their utility.

package com.vinraj.iterable;

import java.util.ArrayList;
import java.util.List;

import com.google.common.collect.Iterables;

public class IterableCompareTest {

    public static void main(String[] args) {
	List<Integer> list1 = new ArrayList<Integer>();
	List<Integer> list2 = new ArrayList<Integer>();

	list1.add(Integer.valueOf(1));
	list1.add(Integer.valueOf(2));
	list1.add(Integer.valueOf(3));

	list2.add(Integer.valueOf(1));
	list2.add(Integer.valueOf(2));
	list2.add(Integer.valueOf(3));

	boolean isEqual = Iterables.elementsEqual(list1, list2);
	System.out.println(isEqual);

    }
}

This utility method would prove to be extremely useful in comparing two collection objects and determining equality of two collection objects. Moving on to the next Google Collection class Comparators. The Comparators class provides a number of utility methods like max, min, compare etc. The program below explains the usage of the max function.

package com.vinraj.comparators;

public class Money implements Comparable<Money>{

    private String currency = null;

    private Double amount = null;

    public Money(String currency, Double amount) {
	this.currency = currency;
	this.amount = amount;
    }

    public int compareTo(Money o) {
	int lessThan = -1;
	int greaterThan = 1;
	int equal = 0;

	if (o == null) {
	    return lessThan;
	}

	//The currency does not match
	if (!this.currency.equals(o.currency)) {
	    return lessThan;
	} else {
	    //The currency matches
	    if (this.amount > o.amount) {
		return greaterThan;
	    } else if (this.amount < o.amount) {
		return lessThan;
	    }

	    //Should match the equals response
	    assert this.equals(o) : "The object does not satisfy "  +
	        "the equality criteria.";
    	    return equal;
	}
    }

    @Override
    public boolean equals(Object o) {
	if (o == null) {
	    return false;
	}

	if (o instanceof Money) {	

	    Money money = (Money)o;

	    if (this.currency == money.currency &&
		this.amount == money.amount) {
	        return true;
	    } else {
	        return false;
	    }

	} else {
	    return false;
	}

    }

    @Override
    public int hashCode() {
	int hash = 0;
	if (this.currency == null) {
	    hash += 10;
	} else {
	    hash += 10 * this.currency.hashCode();
	}

	if (this.amount == null) {
	    hash += 100;
	} else {
	    hash += 100 * this.amount.hashCode();
	}
	    return hash;
    }

    @Override
    public String toString() {
	StringBuilder sb = new StringBuilder();
	sb.append("Money:....... ");
	sb.append("\n");
	sb.append("\tCurrency: ");
	if (this.currency == null) {
	    sb.append("[Not Available]");
	} else {
	    sb.append(this.currency);
	}
	sb.append("\n");
	sb.append("\tAmount: ");
	if (this.amount == null) {
	    sb.append("[Not Available]");
	} else {
	    sb.append(this.amount);
	}

        return sb.toString();

    }

}
package com.vinraj.comparators;

import com.google.common.collect.Comparators;

public class ComparatorsTest {

    public static void main(String[] args) {

	//Using the max function
	Money money1 = new Money("USD", Double.valueOf(124.45));
	Money money2 = new Money("USD", Double.valueOf(124.45001));
	Money money = Comparators.max(money1, money2);
	System.out.println(money);

    }

}

The console output is as follows:

Money:.......
	Currency: USD
	Amount: 124.45001

The Comparators class provides compare utility method for comparing primitive data types like byte, char, short, int, long, double, float etc.

Collections can have null values. Comparators class provides utility methods nullLeastOrder and nullGreatestOrder for handling null values. As per the method name, the null value is appropriately treated as the largest or the smallest value in the collection. Both the methods provide overloaded methods to allow custom Comparator. The following program explains the usage of the nullLeastOrder method.

package com.vinraj.comparators;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.google.common.collect.Comparators;

public class ComparatorsOrderTest {

    public static void main(String[] args) {

	List<Money> container = new ArrayList<Money>();
	Money money1 = new Money("USD", Double.valueOf(100));
	Money money2 = new Money("USD", Double.valueOf(124.45));
	Money money3 = new Money("USD", Double.valueOf(12.45));
	Money money4 = null;

	container.add(money1);
	container.add(money2);
	container.add(money3);
	container.add(money4);

	Comparator comp = Comparators.nullLeastOrder(new MoneyComparator());
	Collections.sort(container, comp);

	System.out.println(container);

    }
}
package com.vinraj.comparators;

import java.util.Comparator;

public class MoneyComparator implements Comparator<Money> {

    public int compare(Money o1, Money o2) {
	return o1.compareTo(o2);
    }
}

The console output is:

[null,
Money:.......
	Currency: GBP
	Amount: 100.0,
Money:.......
	Currency: USD
	Amount: 12.45,
Money:.......
	Currency: USD
	Amount: 124.45]

There are a number of times when a developer wants to compare two objects and determine if the objects are equal in terms of their attribute and relationship values. I have created a sample Person and Address classes and tested their equality using Google Collections’s Objects class.

package com.vinraj.objects;

import java.util.ArrayList;
import java.util.List;

public class Person {

    private String firstName = null;

    private String lastName = null;

    private java.util.Date dob = null;

    private List<Address> addresses = null;

    public List<Address> getAddresses() {
	return addresses;
    }

    public void addAddresses(Address address) {
	if (addresses == null) {
	    this.addresses = new ArrayList<Address>();
	}
	    this.addresses.add(address);
    }

    public java.util.Date getDob() {
	return dob;
    }

    public void setDob(java.util.Date dob) {
	this.dob = dob;
    }

    public String getFirstName() {
	return firstName;
    }

    public void setFirstName(String firstName) {
	this.firstName = firstName;
    }

    public String getLastName() {
	return lastName;
    }

    public void setLastName(String lastName) {
	this.lastName = lastName;
    }

    public boolean equals(Object o) {

	if (o == null) {
	    return false;
	}
	Person person = null;
	if (o instanceof Person) {
	    person = (Person)o;
	} else {
	    return false;
	}

	if (this.equals(this.firstName, person.firstName)) {

	    if (this.equals(this.lastName, person.lastName)) {

	        if (this.equals(this.dob, person.dob)) {

		    if (this.addresses.equals(person.addresses)) {
			return true;
		    } else {
			return false;
		    }

		} else {
		    return false;
		} //End of dob CONDITION

	    } else {
	        return false;
	    } //End of lastName CONDITION

	} else {
	    return false;
	} //End of firstName CONDITION

    }

    private boolean equals(String o1, String o2) {

	if (o1 == null && o2 == null) {
	    return true;
	} else {

	    if ((o1 == null && o2 != null) || (o1 != null && o2 == null)) {
		return false;
	    } else {
		//Both the values are not null values
		return o1.equals(o2);
	    }// End of if ((o1 == null && o2 != null) || (o1 != null && o2 == null)) CONDITION

	}//End of if (o1 == null && o2 == null) CONDITION

    }

    private boolean equals(java.util.Date o1, java.util.Date o2) {

	if (o1 == null && o2 == null) {
	    return true;
	} else {

	    if ((o1 == null && o2 != null) || (o1 != null && o2 == null)) {
	        return false;
	    } else {
		//Both the values are not null values
		return o1.equals(o2);
	    }// End of if ((o1 == null && o2 != null) || (o1 != null && o2 == null)) CONDITION

	}//End of if (o1 == null && o2 == null) CONDITION

    }

    @Override
    public int hashCode() {
	int hash = 0;

	int value = this.firstName != null ? 10 * this.firstName.hashCode() : 10;
	hash += value;

	value = this.lastName != null ? 100 * this.lastName.hashCode() : 100;
	hash += value;

	value = this.dob != null ? 1000 * this.dob.hashCode() : 1000;
	hash += value;

	value = this.addresses != null ? 1000 * this.addresses.hashCode() : 1000;
	hash += value;

	return hash;

    }

}
package com.vinraj.objects;

public class Address {

    private String firstline = null;

    private String secondLine = null;

    private String city = null;

    private Integer zipCode = null;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
	this.city = city;
    }

    public String getFirstline() {
	return firstline;
    }

    public void setFirstline(String firstline) {
	this.firstline = firstline;
    }

    public String getSecondLine() {
	return secondLine;
    }

    public void setSecondLine(String secondLine) {
	this.secondLine = secondLine;
    }

    public Integer getZipCode() {
	return zipCode;
    }

    public void setZipCode(Integer zipCode) {
	this.zipCode = zipCode;
    }

    @Override
    public boolean equals(Object o) {

	if (o == null) {
	    return false;
	}

	Address address = (Address)o;

	boolean isFirstLineEqual = this.firstline == null
	    ? address.firstline == null :
	    this.firstline.equals(address.firstline);
	boolean isSecondLineEqual = this.secondLine == null
	    ? address.secondLine == null :
	    this.secondLine.equals(address.secondLine);
	boolean isCityEqual = this.city == null ? address.city == null
	    : this.city.equals(address.city);
	boolean isZipCodeEqual = this.zipCode == null ? address.zipCode == null :
	    this.zipCode.equals(address.zipCode);

	if (isFirstLineEqual && isSecondLineEqual && isCityEqual
	    && isZipCodeEqual) {
   	    return true;
	}

	    return false;

	}
    }

    @Override
    public int hashCode() {
	int hashCode = 0;

	int value = this.firstline != null ? 10 * this.firstline.hashCode() : 10;
	hashCode += value;

	value = this.secondLine != null ? 100 * this.secondLine.hashCode() : 100;
	hashCode += value;

	value = this.city != null ? 1000 * this.city.hashCode() : 1000;
	hashCode += value;

	value = this.zipCode != null ? 10000 * this.zipCode.hashCode() : 10000;
	hashCode += value;

	return hashCode;

    }
}

package com.vinraj.objects;

import com.google.common.base.Objects;

public class ObjectsTest {

    public static void main(String[] args) {

	java.util.Date dob = new java.util.Date();
	Person person1 = new Person();
	person1.setDob(dob);
	person1.setFirstName("Billy");
	person1.setLastName("Duke");

	Address address1 = new Address();
	address1.setFirstline("1200 Manchester");
	address1.setSecondLine("Old City Lane");
	address1.setCity("London");

	Address address2 = new Address();
	address2.setFirstline("1200 Downing St");
	address2.setSecondLine("Old City Lane");
	address2.setCity("Lynchburg");		

	person1.addAddresses(address1);
	person1.addAddresses(address2);

	Person person2 = new Person();
	person2.setDob(dob);
	person2.setFirstName("Billy");
	person2.setLastName("Duke");

	Address address3 = new Address();
	address3.setFirstline("1200 Manchester");
	address3.setSecondLine("Old City Lane");
	address3.setCity("London");

	person2.addAddresses(address3);
	person2.addAddresses(address2);

	System.out.println(Objects.equal(person1, person2));

    }

}

Besides equals method the Objects class provides other useful methods like deepHashCode, deepToString, deepEquals, hashCode etc. The following toString implementation is added in the Person class.

@Override
public String toString() {

    StringBuilder sb = new StringBuilder();
    sb.append("\n");
    sb.append("Person [\n");
    sb.append("\t First Name: " + this.firstName == null ?
	"[Not Available]" : this.firstName);
    sb.append("\n");
    sb.append("\t Last Name: " + this.lastName == null ?
	"[Not Available]" : this.lastName);
    sb.append("\n");
    sb.append("\t DOB: " + this.dob == null ?
	"[Not Available]" : this.dob);
    sb.append("\n");

    return sb.toString();

}

Sample usage of each of Objects methods is explained below:

package com.vinraj.objects;

import com.google.common.base.Objects;

public class ObjectsOthersTest {

    public static void main(String[] args) {

	java.util.Date dob = new java.util.Date();
	Person person1 = new Person();
	person1.setDob(dob);
	person1.setFirstName("Billy");
	person1.setLastName("Duke");

	Address address1 = new Address();
	address1.setFirstline("1200 Manchester");
	address1.setSecondLine("Old City Lane");
	address1.setCity("London");

	//Using varargs hashCode
	int hashCode = Objects.hashCode(person1, address1);
	System.out.println("varargs hashCode");
	System.out.println(hashCode);

	Person person2 = new Person();
	person2.setDob(dob);
	person2.setFirstName("Clark");
	person2.setLastName("Kent");

	//deepToString
	Person[] persons = {person1, person2};

	//toString output
	System.out.println("toString output");
	System.out.println(persons);
	//Objects.deepToString output
	System.out.println("deepToString output");
	System.out.println(Objects.deepToString(persons));

	//deepHashCode

	//Default hashCode implementation
	System.out.println("default hashCode output");
	System.out.println(persons.hashCode());
	System.out.println("deep hashCode output");
	System.out.println(Objects.deepHashCode(persons));

    }
}

A number of times while using HashMap or Hashtable we have encountered a scenario where we need the value to be a Collection object instead of a inbuilt or custom java object. The ArrayListMultimap class addresses this very issue. Below is a sample program that would help us understand the class usage better.

package com.vinraj.multimap;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multiset;

public class ArrayListMultiMapTest {

    public static void main(String[] args) {

	ArrayListMultimap<String, Integer> map
	    = new ArrayListMultimap<String, Integer>();
	map.put("First", Integer.valueOf(1));
	map.put("First", Integer.valueOf(2));
	map.put("Second", Integer.valueOf(10));
	map.put("Second", Integer.valueOf(15));

	//Retreiving value using the "First" key.
	List<Integer> values = map.get("Second");
	System.out.println(values);

	//Utility method to verify if a given key value combination is present
	//in the multimap
	boolean isPresent = map.containsEntry("First", Integer.valueOf(2));
	System.out.println(isPresent);
	isPresent = map.containsEntry("First", Integer.valueOf(20));
	System.out.println(isPresent);

	//Normal map function to verify if a key is present in the map.
	isPresent = map.containsKey("First");
	System.out.println("is \"First\" present as a key " + isPresent);
	isPresent = map.containsKey(Integer.valueOf(1));
	System.out.println("is 1 present as a key " + isPresent);
	//Normal map function to verify if a value is present in the map
	//Only twist is that the value present within Collection is compared
	isPresent = map.containsValue(Integer.valueOf(1));
	System.out.println("is 1 present as a value " + isPresent);
	isPresent = map.containsValue(Integer.valueOf(15));
	System.out.println("is 15 present as a value " + isPresent);
	isPresent = map.containsValue(Integer.valueOf(150));
	System.out.println("is 150 present as a value " + isPresent);

	//The keys method returns the keys present in the map. Normally the
	//set returned back via Java HashMap keys method is a unique set of all
	//the keys defined within the Map. Here the same key
	//can be present multiple times depending upon the number
	//of values associated with the key. Google Collections
	//has prepared a special class Multiset to handle such scenarios.
	Multiset<String> mset = map.keys();
	System.out.println("MultiSet size: " + mset.size() + "\n" + mset);
	//The keySet method is in line with a typical Java Collections
	//keySet method implementation
	Set<String> set = map.keySet();
	System.out.println("Set size: " + set.size() + "\n" + set);
	//Utility method to remove specific key value pair entry from the map
	 boolean removed = map.remove("First", Integer.valueOf(1));
	 System.out.println("Removal completed: " + removed + "\n" + map);
	//Utility method to remove the key and all associated key values.
	 List<Integer> intValues = map.removeAll("Second");
	 System.out.println("Removal completed: " + removed + "\nInteger Values: "
	     + intValues + "\nmap " + map);
	map.put("Third", Integer.valueOf(1000));
	map.put("Third", Integer.valueOf(2000));
	System.out.println("map: " + map);
	List<Integer> ints = new ArrayList<Integer>();
	ints.add(Integer.valueOf(500));
	ints.add(Integer.valueOf(600));
	//the replaceValues method provides the developer with the ability to replace
	// an existing map key with changed value collection
	List<Integer> intVals =map.replaceValues("Third", ints);
	System.out.println("map after replacement: " + map + "\n" +
	    "Returned List: " + intVals);
	Collection<Integer> vals = map.values();
	System.out.println("Values: " + vals);

    }
}

The output is:

[10, 15]
true
false
is "First" present as a key true
is 1 present as a key false
is 1 present as a value true
is 15 present as a value true
is 150 present as a value false
MultiSet size: 4
[First x 2, Second x 2]
Set size: 2
[First, Second]
Removal completed: true
{First=[2], Second=[10, 15]}
Removal completed: true
Integer Values: [10, 15]
map {First=[2]}
map: {First=[2], Third=[1000, 2000]}
map after replacement: {First=[2], Third=[500, 600]}
Returned List: [1000, 2000]
Values: [2, 500, 600]

A number of times we need a Map that provides two navigability. We would like to navigate to the value via the key and also do viceversa i.e. get the key for a given value. The Java Collections library does not provide any solution for this requirement. Google Collections has come up with a solution via its BiMap implementation. The following program shows some light around the BiMap usage and the utility methods it offers to developers.

package com.vinraj.map;

import com.google.common.collect.BiMap;
import com.google.common.collect.Maps;

public class BiMapTest {

    public static void main(String[] args) {

	BiMap<String, Integer> map = Maps.newHashBiMap();

	map.put("First", Integer.valueOf(1));
	map.put("Second", Integer.valueOf(2));
	map.put("Third", Integer.valueOf(3));
	map.put("Four", Integer.valueOf(4));

	//Uncomment the line below and run the program.
	//An IllegalArgumentException is thrown.
	//map.put("Five", Integer.valueOf(4));
	BiMap<Integer, String> inverseMap = map.inverse();
	String val = inverseMap.get(Integer.valueOf(2));
	System.out.println("Output: " + val);

	//The forcePut method silently replaces the
        //key/value entry if either exist.
	System.out.println("Earlier Map: " + map);
	map.forcePut("Five", Integer.valueOf(4));
	System.out.println("Map after forcePut: " + map);
	map.forcePut("Second", Integer.valueOf(10));
	System.out.println("Map after forcePut: " + map);

    }

}

Console output:

Output: Second
Earlier Map: {First=1, Four=4, Third=3, Second=2}
Map after forcePut: {First=1, Third=3, Five=4, Second=2}
Map after forcePut: {First=1, Third=3, Five=4, Second=10}

Google Collections provides a number of utility classes for operations on Maps, Lists and Sets. This post will not cover the utility classes, the javadoc available with these classes is pretty much self-explanatory. During program development we sometimes feel the need to be able to put in specific rules on the type of objects that could be added in a list. Assume we have a list of Person class and we want to enforce a constraint that only persons with age greater than 18 would be allowed in the list. Google Collections provide a neat trick to handle such constraint enforcement.

package com.vinraj.constraints;

import java.util.ArrayList;
import java.util.List;

import com.google.common.collect.Constraints;

public class ConstraintsTest {

    public static void main(String[] args) {
	List<Person> persons = new ArrayList<Person>();

	Person p1 = new Person();
	p1.setAge(9);
	p1.setFirstName("Billy");
	p1.setLastName("Duke");

	Person p2 = new Person();
	p2.setAge(19);
	p2.setFirstName("Clark");
	p2.setLastName("Kent");

	persons.add(p1);
	persons.add(p2);

	//constrainedList implementation
	List<Person> constraintedPersons
	    = Constraints.constrainedList(persons, new PersonConstraint());
	//Note the Person p1 added before passing the list to constraintedList
	//method is retained and remains unvalidated.
	//Only subsequent additions to constraintedPersons list is validated
	//against the constraint.

	Person p3 = new Person();
	p3.setAge(11);
	p3.setFirstName("Bill");
	p3.setLastName("Clinton");
	constraintedPersons.add(p3);

	System.out.println(constraintedPersons);

    }
}

The only one class I am missing out is ClassToInstanceMap. I am not sure where this utility class would be put to use. When I figure that out I should have something out. Until then I am switching off.

Advertisements

7 thoughts on “Google Collections – An Overview with sample tutorials

  1. hi there,

    I was trying to see if I could use google collections for a project and found your tutorial. nice one. Can you make a download of it ? that would be even more useful.

    Also, if you could make your classes junit/testng classes, that would be even more useful for people to learn.

    BR,
    ~A

    RESPONSE:
    Unfortunately I do not have the source code, therefore cannot make a download of the source. I will keep that in mind during my subsequent posts.

  2. A further enhancement to your examples which would also demonstrate another set of nifty utility methods could be done, if you used the provided creator-methods in the Google Collections:

    List intList = Lists.newArrayList();
    List persList = Lists.newArrayList(new Person(“A”), null, new Person(“B”));
    Map map1 = Maps.newHashMap();

    There are quite some handy methods which aid with the creation and initialisation of collection types. Be sure to check out these in the Lists-, Maps- and Sets-classes in the Google Colletions API and also similar ones in the additional collection types.

  3. Kosi2801,

    Google Collections provides a number of features, I have focused on a few in this tutorial. I agree there are a number of handy features which I have not covered.

  4. boolean isEqual = Iterables.elementsEqual(list1, list2);

    List interface has an equals method in JDK with the same behavior. Is this new one really useful?

  5. It is useful in a way because not everything which is an Iterable is automatically a List.

    The .equals from the List interface only works with the given list and something else, while the Iterables.elementsEqual works with any two objects which are implementing the Iterable interface.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s