Concise Collection Initialization using Google Guava

One thing I really like with languages like python, ruby or perl is that they have succinct and elegant way to initialize the collections -  Map, Set and Array.

Collection Literals project is supposed to bring concise initialization syntax to Java. But there is no hope for this until Java 8. There are some hackish ways to do inline initialization of collections particularly using Double Curly Brace Initialization but none of these is elegant and expressive.

Google provides an excellent api of their core libraries called Guava. This library provides some nice utility classes to perform initialization of collections.

For each collection type, Guava provides Utility Classes. e.g. for Lists, there are classes - Lists (utility class for operating with lists) and ImmutableList - (an Immutable version of List). Lets take a look at couple of examples -

Loading ....

References -
  1. http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/001193.html
  2. http://www.c2.com/cgi/wiki?DoubleBraceInitialization
  3. http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained

Reddit Discussion for this post

Comments

Popular posts from this blog

Prefer ThreadLocalRandom over Random

Shortest Distance Graph Algorithms - How do they differ?

Java - One liner to Configure Logging