Java Collection Framework
Java Collection Framework
Key Components
Hierarchy
Vbnet code
java.util.Collection (Interface)
  |- List (Interface)
  
      |- ArrayList, LinkedList, Vector
      
  |- Set (Interface)
  
      |- HashSet, LinkedHashSet, TreeSet
      
  |- Queue (Interface)
  
      |- PriorityQueue, ArrayDeque
      
java.util.Map (Interface)
  |- HashMap, TreeMap, LinkedHashMap
  
Key Interfaces in JCF
     R
    ●     oot interfaceof the framework.
    ● Methods provided:
            ○ add(E e)   ,
                                addAll(Collection<?       extends E> c)
            ○   remove(Object o)    ,
                                           removeAll(Collection<?> c)  ,
                                                                           clear()
            ○    contains(Object o)      ,
                                                containsAll(Collection<?> c)
            ○     size(),
                               isEmpty()
            ○      iterator()
     A
    ●     n ordered collection allows duplicate elements.
    ● Examples:ArrayList,LinkedList, Vector
    ● Methods in addition to
                                Collection
                                          :
            ○   get(int index),set(int index, E element)
            ○    add(int index, E element)
            ○     remove(int index)
            ○      indexOf(Object o),
                                           lastIndexOf(Object o)
            ○       subList(int fromIndex, int toIndex)
     A
    ●      collection that doesnot allow duplicate elements.
    ● Examples:  HashSet ,
                                  LinkedHashSet  ,
                                                     TreeSet
     ● Key Characteristics:
             ○ No guarantee of order inHashSet  .
            ○ Ordered in insertion sequence for
                                                   LinkedHashSet.
            ○ Sorted in natural or custom order for
                                                       TreeSet
                                                              .
     A
    ●      collection forFIFO(First-In-First-Out) operations.
    ● Examples:  PriorityQueue,    ArrayDeque
     ● Key Methods:
             ○ offer(E e)    : Adds an element.
            ○poll(): Retrieves and removes the head.
             
            ○   peek(): Retrieves the head without removing it.
     A
    ●      collection forkey-value pairs.
    ● Examples:  HashMap   ,
                                    TreeMap
                                           ,
                                              LinkedHashMap
     ● Methods:
              ○   put(K key, V value),   putAll(Map<? extends K, ? extends V>
                     m)
              ○    get(Object key),remove(Object key)
               ○   containsKey(Object key),  containsValue(Object value)
                ○  keySet()
                              ,
                                 values() ,
                                              entrySet()
Characteristics
   
   ●        ses adynamic arrayto store elements.
           U
   ●     Allowsrandom access(via index).
    ●     Not synchronized(unsuitable for multithreading withoutexternal synchronization).
     ●     Allows duplicate elements.
    S
   ●     toring ordered data with frequent read operations.
   ● Maintaining a list of elements without worrying about duplicates.
Example Code
Java code
import java.util.ArrayList;
Internal Working
     1. D  ynamic Resizing: When the internal array is full,the size is increased by50%(in
            JDK 1.8 and above).
      2. Complexity:
                ○ 
                    add(E e): O(1) (amortized)
             ○get(int index): O(1)
              
             ○   remove(int index)  : O(n)
LinkedList
Characteristics
      . D
     1       ynamic in size: No need to resize like an array.
     2. Efficient insertions and deletions: Especially in the middle of the list (O(1) for
            adding/removing nodes).
      3. Sequential access: No random access (O(n) for   get(intindex)   ).
  nderlying Data
 U                                 Dynamic Array                  Doubly Linked List
 Structure
     Implementingqueues or stacks.
   ●
   ● Frequent insertions or deletions at the start, middle, or end.
Example Code
Java code
import java.util.LinkedList;
Set Interface
 ext, let’s dive intoSet, an interface designed forcollections whereduplicates are not
N
allowed.
Key Implementations
    1. HashSet:
              ○ Backed by aHashMapinternally.
               ○ No guarantee of order.
                ○ Fast operations (O(1) for add, remove, and contains).
     2. LinkedHashSet:
                 ○ Extends
                              HashSet, but maintainsinsertion order.
               Slightly slower than
             ○                           HashSetdue to additional overhead.
    3. TreeSet:
             ○ Implements   NavigableSet.
              ○ Backed by aRed-Black Tree.
               ○ Maintains elements insorted order.
                ○ Operations like add, remove, and contains takeO(logn)time.
      U
     ●      ses a self-balancingRed-Black Tree.
     ● Maintains abinary search treewhere the left subtreehas smaller values, and the
           right subtree has larger values.
      ● Ensures logarithmic time complexity for key operations.
Map Interface
A
   Maprepresents a collection ofkey-value pairswhere:
      E
     ●     ach key is unique.
     ● A key maps to exactly one value (no duplicate keys allowed, but duplicate values are
          allowed).
 get(Object key)
                                     Retrieves the value associated with the key.
 remove(Object key)
                                     Removes the mapping for a key.
 containsKey(Object key) Checks if a key exists.
 
 ontainsValue(Object
 c                                    Checks if a value exists.
 value)
 
 keySet()
                                     Returns a
                                                 Setview of all keys.
 values()
                                     Returns a
                                                 Collectionview of all values.
 entrySet()
                                     Returns a
                                                 Setview of all key-value pairs
                                      (
                                         Map.Entry).
Implementations of Map
1. HashMap
    U
   ●      ses ahash tablefor storing key-value pairs.
   ● Order of keys is not guaranteed.
    ● Allows one null key and multiple null values.
Example Code
Java code
import java.util.HashMap;
2. LinkedHashMap
   ● Extends
                HashMapand maintains theinsertion orderof keys.
        lightly slower than
   ● S                     HashMapdue to the additionaloverhead of maintaining the
       order.
Example Code
Java code
import java.util.LinkedHashMap;
3. TreeMap
     Implements
   ●                  NavigableMap, backed by aRed-Black Tree.
   ● Maintains keys insorted order(natural order or asper a custom comparator).
    ● Doesnot allow null keysbut permits null values.
Example Code
Java code
import java.util.TreeMap;
Null Keys Allows one null key Allows one null key Does not allow null keys
  erformanc O
 P             (1) for most                  (1) for most
                                              O                              (log n) for all
                                                                            O
 e          operations                    operations                  operations
 
A  NavigableMapis a subinterface of
                                      SortedMapand provides methods to navigate
through the keys in a map.
Key Methods
                 Method                                   Description
 firstEntry()
                                       Retrieves the first key-value pair.
 lastEntry()
                                       Retrieves the last key-value pair.
 lowerKey(K key)
                                       Returns the greatest key strictly less than
                                                                                     key.
 higherKey(K key)
                                   Returns the smallest key strictly greater than
                                     key.
 ubMap(K fromKey, K
 s                                  Returns a view of the map within a key range.
 toKey)
 
Example
Java code
import java.util.TreeMap;
            grades.put(60, "Pass");
             grades.put(75, "Good");
              grades.put(90, "Excellent");
Synchronization in Collections
 y default, most classes in the Java Collection Framework arenot thread-safe. This means
B
multiple threads modifying or accessing a collection concurrently can lead to unexpected
 behavior.
    . D
   1      ata Corruption: Simultaneous updates to the collection can corrupt its state.
   2. Concurrent Modification Exception: If one thread modifiesa collection while
         another is iterating over it, this exception is thrown.
Thread-Safe Collections
 he
T     Collectionsutility class provides static methodsto create synchronized (thread-safe)
versions of collections.
Example Code
Java code
import java.util.*;
Method Description
 ollections.synchronizedList(L R
 C                                eturns a synchronized
 ist)
                                List.
                                 
Limitations
Key Classes
Class Description
 ConcurrentHashMap
                               Thread-safe, highly efficient implementation of
                                                                                 Map.
 BlockingQueue
                                ueue with blocking methods (
                                Q                             LinkedBlockingQueue
                                                                                 ,
 (Interface)                  etc.).
ConcurrentHashMap
            // Iterate
             scores.forEach((key, value) -> {
                   System.out.println(key + ": " + value);
              });
      }
      
}
CopyOnWriteArrayList
Java code
import java.util.concurrent.CopyOnWriteArrayList;
BlockingQueue
Java code
import java.util.concurrent.ArrayBlockingQueue;
 
A  Comparatoris an interface used to define customsorting logic for objects. It is typically
used when:
     ● You need a sorting order different from the natural order defined by
                                                                               Comparable
                                                                                         .
     ● The objects being compared do not implement
                                                      Comparable
                                                                .
Key Points About Comparator
 unctional Interface: Introduced in Java 8,
F                                              Comparatoris a functional interface with a
single abstract method:
 Java code
int compare(T o1, T o2);
     1.
               R
              ○      eturns a negative value if
                                                 o1is less than
                                                                  o2
                                                                    .
              ○ Returns zero if they are equal.
               ○ Returns a positive value if
                                                o1is greater than
                                                                    o2 .
     2. Default Methods:
                              Comparatorhas several default methodsintroduced in Java 8:
              ○reversed()
                            : Reverses the sorting order.
               
              ○   thenComparing(): Chains multiple comparators for complexsorting.
Implementing Comparator
Java code
class Person {
    String name;
    
    int age;
    
       / Constructor
       /
       public Person(String name, int age) {
       
           this.name = name;
            this.age = age;
       }
       
       Override
       @
       public String toString() {
       
           return name + " (" + age + ")";
       }
       
}
Comparator Implementation
Java code
import java.util.*;
In Java 8+, we can simplify the above code using a lambda expression:
Java code
ollections.sort(people, (p1, p2) -> Integer.compare(p1.age,
C
p2.age));
Java code
people.sort((p1, p2) -> Integer.compare(p1.age, p2.age));
Example 3: Sorting with
                         thenComparing
If we want to sort people by age and, for people with the same age, by name alphabetically:
Java code
import java.util.*;
Java code
eople.sort(Comparator.comparingInt((Person p) ->
p
p.age).reversed());
            map.put(1, "One");
             map.put(3, "Three");
              map.put(2, "Two");
      W
     ●     e need to remove elements during iteration.
     ● We want to traverse elements without exposing the underlying structure.
Types of Iterators
Iterator Example
Java code
import java.util.*;
ListIterator Example
Java code
import java.util.*;
Spliterator Example
The
     Spliteratorsplits the collection into parts for parallel processing. Example:
Java code
import java.util.*;
      . F
     1      unctional-style operations(like
                                               map
                                                  ,
                                                     filter
                                                           , and
                                                                  reduce).
     2. Lazy evaluation, meaning intermediate operations are not executed until a terminal
           operation is invoked.
    3. Pipeline processing, where data flows through a seriesof operations.
Streams do not store data; they process data from collections or other sources.
     S
    ●      implifies complex collection operations (like filtering or mapping).
    ● Enables parallel processing with minimal effort.
     ● Enhances readability and maintainability.
Stream Operations
 ollections:
C
Java code
ist<String> names = List.of("Java", "Python", "C++");
L
Stream<String> stream = names.stream();
 rrays:
A
Java code
tring[] languages = {"Java", "Python", "C++"};
S
Stream<String> stream = Arrays.stream(languages);
 tatic Methods:
S
Java code
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);
2. Intermediate Operations
filter()
Java code
ist<String> names = List.of("Avinash", "Kumar", "Jha", "Java");
L
names.stream()
     .filter(name -> name.startsWith("J"))
     
     .forEach(System.out::println); // Output: Jha, Java
     
map()
Java code
ist<String> names = List.of("Avinash", "Kumar");
L
names.stream()
     .map(String::toUpperCase)
     
     .forEach(System.out::println); // Output: AVINASH, KUMAR
     
sorted()
Java code
ist<Integer> numbers = List.of(5, 3, 8, 1);
L
numbers.stream()
       .sorted()
       
       .forEach(System.out::println); // Output: 1, 3, 5, 8
       
distinct()
Java code
ist<Integer> numbers = List.of(1, 2, 2, 3, 4, 4);
L
numbers.stream()
       .distinct()
       
       .forEach(System.out::println); // Output: 1, 2, 3, 4
       
Java code
tream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
S
stream.limit(3).forEach(System.out::println); // Output: 1, 2, 3
stream.skip(2).forEach(System.out::println); // Output: 3, 4, 5
forEach()
Java code
ist<String> names = List.of("Java", "Python");
L
names.stream().forEach(System.out::println);
collect()
Java code
ist<String> names = List.of("Java", "Python");
L
List<String> upperCaseNames = names.stream()
                                   .map(String::toUpperCase)
                                   
                                   .collect(Collectors.toList());
                                   
System.out.println(upperCaseNames); // Output: [JAVA, PYTHON]
reduce()
Java code
ist<Integer> numbers = List.of(1, 2, 3, 4);
L
int sum = numbers.stream()
                 .reduce(0, Integer::sum); // Initial value is 0
System.out.println(sum); // Output: 10
count()
   ● nyMatch()
       a         : Returns trueif any element matches thepredicate.
    
   ●   allMatch(): Returnstrueif all elements match thepredicate.
   ● 
       noneMatch()  : Returns
                                trueif no elements match thepredicate.
Example:
Java code
ist<Integer> numbers = List.of(2, 4, 6, 8);
L
boolean allEven = numbers.stream().allMatch(n -> n % 2 == 0);
System.out.println(allEven); // Output: true
Java code
ist<Integer> numbers = List.of(1, 2, 3, 4, 5);
L
numbers.parallelStream()
       .map(n -> n * n)
       
       .forEach(System.out::println); // Order is not guaranteed
       
Practical Examples
Using
       Collectors.groupingBy():
Java code
ist<String> items = List.of("Apple", "Banana", "Cherry",
L
"Avocado");
Map<Character, List<String>> groupedByFirstLetter = items.stream()
    .collect(Collectors.groupingBy(item -> item.charAt(0)));
    
System.out.println(groupedByFirstLetter);
// Output: {A=[Apple, Avocado], B=[Banana], C=[Cherry]}