Creating singleton collections

The Collections class in the java.util package provides convenient methods to create singleton collection objects. A singleton collection object is a List, Map or Set that contains only a single element. Here’s how you can create a singleton set:

Set set = Collections.singleton( "The Element" );

There are 2 more methods which allow you to create a singleton list or map:

List list = Collections.singletonList( "The Element" );
Map map = Collections.singletonMap( "Key" , "Value" );

The collection object returned in all these methods is an immutable object. Also, all 3 of them are static methods in the Collections class.

Leave a Reply

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 )

Connecting to %s