# Week 7: Java Collections Framework ## Objectives 1. Understand the Java Collections Framework 2. Learn about Lists, Sets, and Maps 3. Explore utility methods in the Collections class 4. Introduce the Stream API for processing collections --- ## Java Collections Framework Overview - A unified architecture for representing and manipulating collections - Reduces programming effort and increases program speed and quality - Core interfaces: Collection, Set, List, Queue, and Map - Implementation classes: ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, etc. - Utility class: Collections --- ## Collections vs Arrays: | Feature| Collections| Arrays| |--------------|--------------------------------------------------|---------------------------------------------| | Flexibility| More flexible and provide additional functionality | Fixed size and less flexible| | Storage| Can store objects | Can store primitives | | Resizing| Can be resized dynamically | Have a fixed size | | Operations | Provide more operations like add, remove, and search | Efficient for simple operations like access and iteration | | Preference | Preferred in most cases due to flexibility and functionality | Useful for simple data structures and performance-critical code | | Part of | Java Collections Framework | Basic language feature | --- ###  --- ## ADTs - Does not dictate how the data is organized - Dictates the operations that can be performed on the data - Concrete data structure is usually a concrete class - Abstract Data Type is usually an interface --- ## Lists - is a Abstract Data Type (ADT) - Ordered collection (sequence) - Elements can be accessed by their integer index - Allows duplicate elements - Main implementations: - ArrayList: Dynamic array implementation - LinkedList: Doubly-linked list implementation ~.~ --- ## Sets - Collection that cannot contain duplicate elements - Models the mathematical set abstraction - Main implementations: - HashSet: Uses a hash table for storage - TreeSet: Uses a tree for storage, elements are ordered - LinkedHashSet: Hash table with linked list, preserves insertion order ~.~ --- ## Maps - Object that maps keys to values - Cannot contain duplicate keys - Each key can map to at most one value - Main implementations: - HashMap: Uses a hash table for storage - TreeMap: Uses a tree for storage, keys are ordered - LinkedHashMap: Hash table with linked list, preserves insertion order ~.~ --- ## Utility Methods in Collections Class - Collections class provides static methods to operate on or return collections - Common methods: - sort(): Sorts a List - binarySearch(): Searches for an element in a sorted List - reverse(): Reverses the order of elements in a List - shuffle(): Randomly permutes a List - min() and max(): Returns the minimum or maximum element - Benefits of Using Java Collections Framework - Consistent API: All collections support operations like add, remove, and clear. - Reduces effort: Eliminates the need to write data structures from scratch. - Increases program speed and quality: Implementations are high-performance and well-tested. - Allows interoperability: Collections can be easily converted from one type to another. - Encourages software reuse: Algorithms are written in terms of interfaces, not implementations. --- ## Comparable Vs Comparator | Feature | Comparable | Comparator | |---------|------------|------------| | Interface | `java.lang.Comparable` | `java.util.Comparator` | | Method to implement | `compareTo(T o)` | `compare(T o1, T o2)` | | Part of class | Yes, implemented by the class being compared | No, separate class or lambda | | Number of sort sequences | Single, natural ordering | Multiple, flexible orderings | | Usage with `Collections.sort()` | `Collections.sort(List
)` | `Collections.sort(List
, Comparator
)` | | Usage with `Arrays.sort()` | `Arrays.sort(T[])` | `Arrays.sort(T[], Comparator
)` | | When to use | When there's a single, natural ordering | When multiple orderings are needed or can't modify the original class | | Example implementation | `class Student implements Comparable
{ ... }` | `class StudentAgeComparator implements Comparator
{ ... }` | | Lambda expression support | N/A | `(s1, s2) -> s1.getAge() - s2.getAge()` | | Method reference support | N/A | `Comparator.comparing(Student::getName)` | --- ## Introduction to Stream API - Introduced in Java 8 - Allows functional-style operations on streams of elements - A stream is a sequence of elements supporting sequential and parallel aggregate operations - Key features: - Pipeline processing - Internal iteration - Lazy evaluation - Parallelism --- ## Stream API Operations ~.~ - Two types of operations: 1. Intermediate operations: Return a new stream (e.g., filter, map, sorted) 2. Terminal operations: Produce a result or side-effect (e.g., forEach, collect, reduce) - Example: ```java List
myList = Arrays.asList("a1", "a2", "b1", "c2", "c1"); myList.stream() .filter(s -> s.startsWith("c")) .map(String::toUpperCase) .sorted() .forEach(System.out::println); ``` --- ## Functional Programming: - Treats computation as the evaluation of mathematical functions. - Avoids changing state and mutable data. - Examples: Haskell, Lisp, Scala - Used in: Data processing, parallel computing, AI - Characteristics: Immutability, first-class functions, recursion ### Benefits of Functional Programming: - Easier to debug and test (pure functions) - Better support for parallel/concurrent programming - More predictable code behavior - Often more concise and expressive --- ### **Functional Interfaces in Java** #### **What is a Functional Interface?** - An interface with exactly **one abstract method**. - Can have **multiple default and static methods**. - Used primarily for **lambda expressions** and **method references**. **Key Annotation** ```java @FunctionalInterface interface MyFunctionalInterface { void doSomething(); } ``` - The `@FunctionalInterface` annotation is optional but helps enforce the rule. ~.~ --- ## Knowledge Check ### http://quiz.codewithme.com ###  --- ## Additional Resources - Java Documentation: [Java Collections Framework](https://docs.oracle.com/javase/8/docs/technotes/guides/collections/) - Tutorial: [Java 8 Streams Tutorial](https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/) ```