Introduction to Collections in Java
Java Collections Framework provides a set of interfaces and classes to store and manipulate groups of objects efficiently. It is a unified architecture to represent and manage collections such as lists, sets, queues, and maps.
Main Collection Interfaces
- List: Ordered collection that allows duplicate elements. Examples include
ArrayList
andLinkedList
. - Set: Collection that does not allow duplicate elements. Examples include
HashSet
andTreeSet
. - Queue: Ordered collection designed for holding elements prior to processing. Examples include
PriorityQueue
andLinkedList
. - Map: Key-value pairs collection that does not allow duplicate keys. Examples include
HashMap
andTreeMap
.
Hierarchy of Collections
The Java Collections Framework is organized as follows:
Collection
|
|-- List (e.g., ArrayList, LinkedList)
|
|-- Set (e.g., HashSet, TreeSet)
|
|-- Queue (e.g., LinkedList, PriorityQueue)
|
|-- Map (e.g., HashMap, TreeMap)
Examples of Key Collections
List Example
List list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Apple"); // Allows duplicates
for (String item : list) {
System.out.println(item);
}
Set Example
Set set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate ignored
for (String item : set) {
System.out.println(item);
}
Map Example
Map map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Apple", 3); // Overwrites key
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Conclusion
The Java Collections Framework simplifies the storage, retrieval, and manipulation of data in Java programs. By choosing the right collection, developers can optimize their code for performance and clarity.
0 Comments