Guava collection initializers

22 08 2015

Java requires quite verbose collection initialization (due to generics) like this:

Map<String, Map<String, Integer>> lookupTraditional = new HashMap<String, Map<String, Integer>>();

It barely fits one line… It’s long and readability is reduced.

Java 7 introduced the Diamond Operator, so the developer does not have to repeat all the types declaration after the new operator:

Map<String, Map<String, Integer>> lookupJava7 = new HashMap<>();

Guava creators’ idea is to use static factory method pattern to shorten the collection initialization:

Map<String, Map<String, Integer>> lookup = Maps.newHashMap();

Factory methods are overloaded to accept params thet fill the collection with items. To create List of names use:

List<String> names = Lists.newArrayList("Bob", "Gwen", "Justin");

Get the code to experiment

If you are willing to experiment with Guava feel free to use my project skeleton with initializers demo:



Give Your feedback:

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

You are commenting using your 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

%d bloggers like this: