Atom Feed SITE FEED   ADD TO GOOGLE READER

Coding in the small with Google Collections: Maps, Sets and Lists

Part 11 in a Series by Jerome Mourits, Guest blogger...

Generics are good, but they can be really wordy!

Before:

Map<CustomerId, BillingOrderHistory> customerOrderHistoryMap 
= new HashMap<CustomerId, BillingOrderHistory>();

After:

Map<CustomerId, BillingOrderHistory> customerOrderHistoryMap 
= Maps.newHashMap();
Look Ma! I don't have to specify my type parameters twice! (The compiler figures it out through Type Inference from Assignment Context). Maps, Sets and Lists contain factory methods to create Collections objects. Here's another useful one:

Before:

Set<String> workdays = new LinkedHashSet<String>();
workdays.add("Monday");
workdays.add("Tuesday");
workdays.add("Wednesday");
workdays.add("Thursday");
workdays.add("Friday");

Or:

Set<String> workdays = new LinkedHashSet<String>(
Arrays.asList("Monday", "Tuesday", "Wednesday", "Thursday", "Friday"));

After:

Set<String> workdays = Sets.newLinkedHashSet(
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday");
Google Collections provides factory methods for Maps, Sets, Lists, Multimaps, Multisets and other types.

Part 12
You're types don't match in the first example:
BillingOrderHistory, CustomerOrderHistory,
CustomerBillingOrderHistory
Whoops! Fixed.
Almost fixed... The After should be consistent with the Before. :-)

Thanks for the great posts.