Wednesday, June 23, 2010

Creating a Collection with a single element

Question: What is the most efficient way of creating a collection (Set, List or Map) with a single element?

Answer: The most efficient way of creating a collection with a single element would be to make use of the Collections.singletonXXX() methods.
  • Collections.singleton - To create a set that has only one element.
  • Collections.singletonList - To create a list that has only one element.
  • Collections.singletonMap - To crate a map that has only one entry.
The collections returned from these methods are immutable.

Compare these methods with Collections.unmodifiableXXX() methods. The umodifiableXXX methods already accept a collection as an argument.

1 comment:

ur3cma said...

Useful info, thanks.