Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Code Trick: Double Brace Initialization [Snippet]

DZone's Guide to

Java Code Trick: Double Brace Initialization [Snippet]

Want to know how to initialize a collection in Java while saving time adding elements to it? See how two sets of braces can help you out.

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

While coding for our current project, I had the following thought: "Is it possible somehow not to write the variable of the collection every time I want to add some elements to it?" So I searched if there is a way to do that and found out a solution that I assume is a code trick in Java. It is not very intuitive, but it was quite easy to use. Below, I will first share the standard initialization we do and then the code trick to show you how it improves the process.

Standard Initialization of a Collection in Java

Usually, we initialize a set this way:

Double Brace Initialization

Now you can see how long a name we have for this set, but this is recommended for quality conventions and a better understanding of the code. In this code snippet, we have written the variable name of the set four times just to add elements to it.

Also, you may want to initialize set as a constant:

Double Brace Initialization

And here we have the same – writing the constant set name before adding an element to it.

Code Trick With Double Brace Initialization

Yes, we can create and initialize a new collection as an expression by using the “double-brace” syntax:

Double Brace Initialization

As you can see, you are able to add elements to the collection on initialization just by using add, without writing the variable name of the collection. I find it very useful when you want to add elements to a collection at the initialization step.

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
java ,double brace initialization ,collection

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}