Collection Overview And Collection
Interface In Java
237R1A05W3
M. N I H A R I K A
CSE-E
Introduction to Java Collections
• Java Collections Framework is a unified architecture for
representing and manipulating collections.
• It provides a set of interfaces, implementations, and
algorithms to work with groups of objects.
• The framework is essential for optimizing data manipulation
and improving code efficiency.
Benefits of Using Collections
• Collections simplify data management by providing built-in
methods for common tasks.
• They enhance performance through optimized data
structures and algorithms.
• Using collections promotes code reusability and reduces
programming complexity.
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
// List Example
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
list.add("Apple"); // Duplicates allowed
System.out.println("List: " + list);
// Set Example
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // Duplicates not
allowed
s system.out.println("set:"+set);
// Map Example
Map<String, Integer> map = new
HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3); ArrayDeque<>();
System.out.println("Map: " + map); deque.addFirst("Apple");
deque.addLast("Banana");
// Queue Example deque.addLast("Cherry");
Queue<String> queue = new System.out.println("Deque: " + deque);
LinkedList<>(); System.out.println("Deque Poll First: "
queue.add("Apple"); + deque.pollFirst()); // Removes the first
queue.add("Banana"); element
queue.add("Cherry"); System.out.println("Deque after Poll
System.out.println("Queue: " + queue); First: " + deque);
System.out.println("Queue Poll: " + }
queue.poll()); // Removes the head of the }
queue
System.out.println("Queue after Poll: "
+ queue);
Key Interfaces in the Collection Framework
• The Collection interface is the root interface in the Java
Collections Framework.
• Other important interfaces include List, Set, and Queue,
each with their own specialized behaviors.
• These interfaces define a contract for collections and
establish a common approach for data manipulation.
The Collection Interface
• The Collection interface defines essential methods for
adding, removing, and querying elements.
• Key methods include `add()`, `remove()`, `size()`, and
`isEmpty()`, which manage the collection's contents.
• It also provides methods for iterating over elements,
facilitating easier access to data.
Conclusion and Best Practices
• Understanding the Collection framework is essential for
effective Java programming.
• Choosing the right collection implementation can
significantly impact performance and memory usage.
• Following best practices, such as using interfaces for
variable types, enhances flexibility and maintainability.