← Back to Home

Module 4 - Executor Service

Module Overview

Learn about Java's Executor Service framework for managing thread pools and executing asynchronous tasks efficiently.

Tree Data Structures

Trees are hierarchical data structures that represent parent-child relationships. They're essential in many areas of programming and computer science.

Key characteristics of trees:

// Basic tree node implementation
public class TreeNode<T> {
    private T data;
    private List<TreeNode<T>> children;
    
    public TreeNode(T data) {
        this.data = data;
        this.children = new ArrayList<>();
    }
    
    public void addChild(TreeNode<T> child) {
        children.add(child);
    }
    
    public T getData() { return data; }
    public List<TreeNode<T>> getChildren() { return children; }
}

Tree Traversal Techniques

Trees can be traversed in different ways depending on your needs. The two primary traversal methods are depth-first and breadth-first.

Key traversal approaches:

// Breadth-first traversal to find a node closest to root
public <T> TreeNode<T> findNodeBFS(TreeNode<T> root, Predicate<T> condition) {
    if (root == null) return null;
    
    Queue<TreeNode<T>> queue = new LinkedList<>();
    queue.add(root);
    
    while (!queue.isEmpty()) {
        TreeNode<T> current = queue.poll();
        
        if (condition.test(current.getData())) {
            return current; // Found a node matching the condition
        }
        
        // Add all children to the queue
        queue.addAll(current.getChildren());
    }
    
    return null; // No matching node found
}

Java TreeMap and TreeSet

Java provides tree-based implementations of Map and Set interfaces that maintain their elements in sorted order. These collections are backed by a balanced binary search tree.

Benefits of tree-based collections:

// Using TreeMap to maintain sorted key-value pairs
import java.util.TreeMap;

public class SortedProductCatalog {
    private TreeMap<String, Double> products = new TreeMap<>();
    
    public void addProduct(String name, double price) {
        products.put(name, price);
    }
    
    public Double getPrice(String productName) {
        return products.get(productName); // O(log n) lookup
    }
    
    public Map.Entry<String, Double> getCheapestProduct() {
        return products.firstEntry(); // O(1) operation once the tree is built
    }
    
    public Map.Entry<String, Double> getMostExpensiveProduct() {
        return products.lastEntry(); // O(1) operation once the tree is built
    }
}

Learning Objectives

Resources