How to create Java collections?
Java collections can be created in several ways:
- Create a collection object using the new keyword.
- We have initialized a new ArrayList for a list of integers, a HashSet for a set of strings, and a HashMap for a map of strings and integers.
- Create a collection object using a collection utility class.
- The code initializes a list with integers 1, 2, and 3, a set with strings “a”, “b”, and “c”, and a map with keys “key1” and “key2” mapped to integers 1 and 2, respectively.
- Create collection objects using a collection factory method.
- Create a list containing integers 1, 2, and 3, a set containing strings “a”, “b”, and “c”, and a map with key-value pairs “key1” – 1 and “key2” – 2.
Note: After creating a collection object, operations such as adding, deleting, and modifying can be performed as needed.