Collection
Course Servelet
1. Overview of Java Collections Framework
Java Collections Framework (JCF): A unified architecture for representing
and manipulating collections of objects.
Core Interfaces:
Collection: The root interface for all collections (e.g., List , Set , Queue ).
Map: A separate interface for key-value pair collections.
2. Key Interfaces and Their Implementations
List Interface:
Characteristics: Ordered, allows duplicates.
Implementations:
ArrayList: Dynamic array, fast random access, not synchronized.
LinkedList: Doubly linked list, efficient for insertions/deletions,
allows null elements.
Vector: Synchronized version of ArrayList , slower due to thread
safety.
Set Interface:
Characteristics: Unordered, no duplicates.
Implementations:
HashSet: Backed by a HashMap , unordered, allows one null element.
LinkedHashSet: Maintains insertion order.
TreeSet: Implements NavigableSet , ordered according to Comparable
or Comparator , no null elements.
Queue Interface:
Characteristics: Follows FIFO (First-In-First-Out) principle.
Collection 1
Implementations:
PriorityQueue: Elements are ordered according to their natural
ordering or a specified Comparator , allows null.
LinkedList: Can be used as both a List and Queue .
Map Interface:
Characteristics: Key-value pairs, keys must be unique.
Implementations:
HashMap: Unordered, allows one null key and multiple null
values.
LinkedHashMap: Maintains insertion order, allows null
keys/values.
TreeMap: Implements NavigableMap , ordered by natural ordering or a
Comparator , no null keys.
Hashtable: Synchronized, no null keys/values, slower than HashMap .
3. Important Methods in Collection Interface
add(E e) : Adds an element to the collection.
remove(Object o) : Removes the first occurrence of the specified element.
contains(Object o) : Returns true if the collection contains the specified
element.
size() : Returns the number of elements in the collection.
isEmpty() : Checks if the collection is empty.
iterator() : Returns an iterator over the elements.
4. Iteration Techniques
Using Iterator :
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Collection 2
Using Enhanced For-Loop:
for (String item : list) {
System.out.println(item);
}
Using forEach and Lambda:
list.forEach(item -> System.out.println(item));
5. Comparison of List Implementations
ArrayList :
Best for: Random access, fewer insertions/deletions.
Internal structure: Dynamic array.
LinkedList :
Best for: Frequent insertions and deletions.
Internal structure: Doubly linked list.
Vector :
Best for: Thread-safe list operations.
Internal structure: Synchronized version of ArrayList .
6. Comparison of Set Implementations
HashSet :
Performance: O(1) for add, remove, and contains.
Uses: When unique elements without order are needed.
LinkedHashSet :
Performance: Similar to HashSet , but maintains insertion order.
TreeSet :
Performance: O(log n) for add, remove, and contains.
Uses: When elements need to be sorted.
Collection 3
7. Comparison of Map Implementations
HashMap :
Performance: O(1) for get and put.
Uses: General-purpose map with no ordering.
LinkedHashMap :
Performance: Slightly slower than HashMap due to maintaining order.
Uses: Maintains insertion order, useful for caching.
TreeMap :
Performance: O(log n) for get and put.
Uses: Sorted map, useful for range-based queries.
Hashtable :
Performance: Slower due to synchronization.
Uses: Thread-safe map, no null keys/values.
8. Thread-Safe Collections
Synchronized Collections:
Use Collections.synchronizedList() , synchronizedSet() , etc., for
synchronized versions.
Example:
List<String> syncList = Collections.synchronizedList
(new ArrayList<>());
Concurrent Collections:
ConcurrentHashMap : High-concurrency map, thread-safe, better
performance than Hashtable .
: Thread-safe variant of
CopyOnWriteArrayList ArrayList , suitable for use
cases with more reads than writes.
9. Common Methods in Map Interface
put(K key, V value) : Inserts a key-value pair into the map.
Collection 4
get(Object key) : Returns the value associated with the key.
remove(Object key) : Removes the key-value pair.
containsKey(Object key) : Checks if the map contains the key.
entrySet() : Returns a set view of the map's entries.
10. Sorting Collections
Using Collections.sort() :
List<String> list = new ArrayList<>(Arrays.asList("Banan
a", "Apple", "Cherry"));
Collections.sort(list); // Natural ordering
Using Custom Comparator:
Collections.sort(list, (s1, s2) -> s1.length() - s2.leng
th());
11. Generics in Collections
Benefits:
Type safety.
Avoids ClassCastException .
Example:
List<String> list = new ArrayList<>();
list.add("Hello");
// list.add(123); // Compile-time error
12. Iterable Interface
Methods:
iterator() : Returns an iterator.
For-Each Loop Compatibility:
Classes that implement Iterable can be iterated using the for-each
loop.
Collection 5
13. Immutable Collections
Use Collections.unmodifiableList() , unmodifiableSet() , unmodifiableMap() for
creating read-only collections.
Example:
List<String> immutableList = Collections.unmodifiableLis
t(new ArrayList<>(Arrays.asList("A", "B", "C")));
14. Stream API with Collections
Example: Filtering a list using streams.
List<String> filteredList = list.stream()
.filter(s -> s.startsWit
h("A"))
.collect(Collectors.toLi
st());
15. Best Practices for Using Collections
Use the right collection: Choose List , Set , Queue , or Map based on the
specific needs.
Initial Capacity: When using ArrayList or HashMap , specify an initial capacity
if the size is known to avoid resizing.
Null Handling: Be cautious with null values, especially in collections like
TreeSet and TreeMap that do not allow null keys.
Thread Safety: For concurrent access, use synchronized or concurrent
collections as appropriate.
Collection 6