Java Samples

Essential Java code examples and Hello World demonstrations

Key Facts

Category
Programming Languages
Items
3
Format Families
sample

Sample Overview

Essential Java code examples and Hello World demonstrations This sample set belongs to Programming Languages and can be used to test related workflows inside Elysia Tools.

💻 Java Hello World java

🟢 simple ⭐⭐

Basic Java Hello World program and fundamental syntax examples

⏱️ 15 min 🏷️ java, programming, oop
Prerequisites: Basic programming concepts
// Java Hello World Examples

public class HelloWorldExamples {
    
    // 1. Basic Hello World
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

// 2. Hello World with methods
class HelloMethods {
    public static void main(String[] args) {
        sayHello();
        greetUser("Java");
    }
    
    public static void sayHello() {
        System.out.println("Hello, World!");
    }
    
    public static void greetUser(String name) {
        System.out.println("Hello, " + name + "!");
    }
}

// 3. Hello World with class and object
class Greeter {
    private String message;
    
    public Greeter() {
        this.message = "Hello, World!";
    }
    
    public Greeter(String message) {
        this.message = message;
    }
    
    public void greet() {
        System.out.println(message);
    }
    
    public void greetUser(String name) {
        System.out.println(message + ", " + name + "!");
    }
}

class GreeterDemo {
    public static void main(String[] args) {
        Greeter greeter1 = new Greeter();
        Greeter greeter2 = new Greeter("Welcome");
        
        greeter1.greet();
        greeter2.greetUser("Java Developer");
    }
}

// 4. Hello World with user input
class HelloInput {
    public static void main(String[] args) {
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        
        System.out.println("Hello, " + name + "!");
        
        scanner.close();
    }
}

// 5. Hello World with command line arguments
class HelloArgs {
    public static void main(String[] args) {
        if (args.length > 0) {
            System.out.println("Hello, " + args[0] + "!");
        } else {
            System.out.println("Hello, World!");
        }
        
        // Print all arguments
        for (int i = 0; i < args.length; i++) {
            System.out.println("Arg " + i + ": " + args[i]);
        }
    }
}

// 6. Hello World with different data types
class DataTypesDemo {
    public static void main(String[] args) {
        // Primitive types
        int age = 25;
        double price = 19.99;
        char grade = 'A';
        boolean isActive = true;
        
        // Reference types
        String name = "Java";
        Integer number = 100;
        
        System.out.println("Hello, " + name + "!");
        System.out.println("Age: " + age);
        System.out.println("Price: " + price);
        System.out.println("Grade: " + grade);
        System.out.println("Active: " + isActive);
        System.out.println("Number: " + number);
    }
}

// 7. Hello World with arrays
class ArrayHello {
    public static void main(String[] args) {
        String[] greetings = {"Hello", "Hola", "Bonjour", "こんにちは", "Ciao"};
        
        // Traditional for loop
        for (int i = 0; i < greetings.length; i++) {
            System.out.println(greetings[i] + ", World!");
        }
        
        // Enhanced for loop
        System.out.println("\nUsing enhanced for loop:");
        for (String greeting : greetings) {
            System.out.println(greeting + ", World!");
        }
    }
}

// 8. Hello World with ArrayList
class ListHello {
    public static void main(String[] args) {
        java.util.List<String> greetings = new java.util.ArrayList<>();
        greetings.add("Hello");
        greetings.add("Hola");
        greetings.add("Bonjour");
        greetings.add("こんにちは");
        
        // Using forEach with lambda
        greetings.forEach(greeting -> {
            System.out.println(greeting + ", World!");
        });
    }
}

// 9. Hello World with HashMap
class MapHello {
    public static void main(String[] args) {
        java.util.Map<String, String> greetings = new java.util.HashMap<>();
        greetings.put("en", "Hello");
        greetings.put("es", "Hola");
        greetings.put("fr", "Bonjour");
        greetings.put("de", "Hallo");
        greetings.put("ja", "こんにちは");
        
        for (java.util.Map.Entry<String, String> entry : greetings.entrySet()) {
            System.out.println(entry.getValue() + ", World! (" + entry.getKey() + ")");
        }
    }
}

// 10. Hello World with file I/O
class FileHello {
    public static void main(String[] args) {
        // Write to file
        try (java.io.FileWriter writer = new java.io.FileWriter("hello.txt")) {
            writer.write("Hello, World!\n");
            writer.write("This is a Java file example.\n");
        } catch (java.io.IOException e) {
            System.err.println("Error writing to file: " + e.getMessage());
        }
        
        // Read from file
        try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader("hello.txt"))) {
            String line;
            System.out.println("File contents:");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (java.io.IOException e) {
            System.err.println("Error reading from file: " + e.getMessage());
        }
    }
}

// 11. Hello World with date and time
class DateTimeHello {
    public static void main(String[] args) {
        java.time.LocalDateTime now = java.time.LocalDateTime.now();
        java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        System.out.println("Hello, World!");
        System.out.println("Current time: " + now.format(formatter));
        
        // Format different ways
        System.out.println("Date: " + now.toLocalDate());
        System.out.println("Time: " + now.toLocalTime());
    }
}

// 12. Hello World with exception handling
class ExceptionHello {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Hello, World!");
            System.out.println("Cannot divide by zero: " + e.getMessage());
        }
        
        // Multiple exceptions
        try {
            String text = null;
            System.out.println(text.length());
        } catch (NullPointerException e) {
            System.out.println("Null pointer caught: " + e.getMessage());
        } finally {
            System.out.println("Finally block executed");
        }
    }
    
    public static int divide(int a, int b) {
        return a / b;
    }
}

// 13. Hello World with threads
class ThreadHello {
    public static void main(String[] args) {
        // Using anonymous class
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 3; i++) {
                    System.out.println("Hello from Thread 1 - " + i);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        
        // Using lambda expression
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                System.out.println("Hello from Thread 2 - " + i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        
        thread1.start();
        thread2.start();
        
        System.out.println("Hello from Main Thread!");
        
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

// 14. Hello World with inheritance
class Animal {
    protected String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public void makeSound() {
        System.out.println("Some sound");
    }
    
    public void greet() {
        System.out.println("Hello, I'm " + name);
    }
}

class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
    
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
    
    public void wagTail() {
        System.out.println("Tail wagging");
    }
}

class InheritanceDemo {
    public static void main(String[] args) {
        Animal animal = new Animal("Generic Animal");
        Dog dog = new Dog("Rex");
        
        animal.greet();
        dog.greet();
        dog.makeSound();
        dog.wagTail();
    }
}

// 15. Hello World with interface
interface Greeting {
    void sayHello();
    void sayGoodbye();
}

class EnglishGreeting implements Greeting {
    public void sayHello() {
        System.out.println("Hello!");
    }
    
    public void sayGoodbye() {
        System.out.println("Goodbye!");
    }
}

class SpanishGreeting implements Greeting {
    public void sayHello() {
        System.out.println("¡Hola!");
    }
    
    public void sayGoodbye() {
        System.out.println("¡Adiós!");
    }
}

class InterfaceDemo {
    public static void main(String[] args) {
        Greeting english = new EnglishGreeting();
        Greeting spanish = new SpanishGreeting();
        
        english.sayHello();
        spanish.sayHello();
        english.sayGoodbye();
        spanish.sayGoodbye();
    }
}

💻 Java Collections Framework java

🟡 intermediate ⭐⭐⭐⭐

Comprehensive examples of Java collections including List, Set, Map, and their implementations

⏱️ 30 min 🏷️ java, collections, data structures
Prerequisites: Basic Java syntax and OOP concepts
// Java Collections Framework Examples

import java.util.*;
import java.util.stream.Collectors;

public class CollectionsFrameworkDemo {

    public static void main(String[] args) {
        listExamples();
        setExamples();
        mapExamples();
        queueExamples();
        streamExamples();
    }

    // 1. List Examples
    public static void listExamples() {
        System.out.println("=== List Examples ===");
        
        // ArrayList
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Apple");
        arrayList.add("Banana");
        arrayList.add("Cherry");
        arrayList.add("Date");
        
        System.out.println("ArrayList: " + arrayList);
        System.out.println("Size: " + arrayList.size());
        System.out.println("Get element at index 1: " + arrayList.get(1));
        
        // Insert at specific index
        arrayList.add(1, "Blueberry");
        System.out.println("After insert: " + arrayList);
        
        // Remove element
        arrayList.remove("Banana");
        System.out.println("After remove: " + arrayList);
        
        // Contains check
        System.out.println("Contains 'Apple': " + arrayList.contains("Apple"));
        
        // Iterator
        System.out.print("Using iterator: ");
        Iterator<String> iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
        
        // LinkedList
        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(10);
        linkedList.add(20);
        linkedList.addFirst(5);
        linkedList.addLast(30);
        
        System.out.println("\nLinkedList: " + linkedList);
        System.out.println("First element: " + linkedList.getFirst());
        System.out.println("Last element: " + linkedList.getLast());
        
        // Vector (thread-safe)
        List<String> vector = new Vector<>();
        vector.add("One");
        vector.add("Two");
        vector.add("Three");
        
        System.out.println("\nVector: " + vector);
        
        // Sorting
        Collections.sort(arrayList);
        System.out.println("Sorted ArrayList: " + arrayList);
        
        // Reverse
        Collections.reverse(arrayList);
        System.out.println("Reversed ArrayList: " + arrayList);
    }

    // 2. Set Examples
    public static void setExamples() {
        System.out.println("\n=== Set Examples ===");
        
        // HashSet (no duplicates, no order)
        Set<String> hashSet = new HashSet<>();
        hashSet.add("Apple");
        hashSet.add("Banana");
        hashSet.add("Apple"); // Duplicate, won't be added
        hashSet.add("Cherry");
        
        System.out.println("HashSet: " + hashSet);
        System.out.println("Size: " + hashSet.size());
        
        // TreeSet (sorted order)
        TreeSet<Integer> treeSet = new TreeSet<>();
        treeSet.add(50);
        treeSet.add(20);
        treeSet.add(80);
        treeSet.add(10);
        treeSet.add(50); // Duplicate, won't be added
        
        System.out.println("\nTreeSet: " + treeSet);
        System.out.println("First element: " + treeSet.first());
        System.out.println("Last element: " + treeSet.last());
        
        // NavigableSet methods
        System.out.println("Floor 30: " + treeSet.floor(30));
        System.out.println("Ceiling 30: " + treeSet.ceiling(30));
        
        // LinkedHashSet (insertion order)
        Set<String> linkedHashSet = new LinkedHashSet<>();
        linkedHashSet.add("Zebra");
        linkedHashSet.add("Apple");
        linkedHashSet.add("Monkey");
        linkedHashSet.add("Banana");
        
        System.out.println("\nLinkedHashSet: " + linkedHashSet);
        
        // Set operations
        Set<Integer> setA = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
        Set<Integer> setB = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8));
        
        Set<Integer> union = new HashSet<>(setA);
        union.addAll(setB);
        System.out.println("\nUnion: " + union);
        
        Set<Integer> intersection = new HashSet<>(setA);
        intersection.retainAll(setB);
        System.out.println("Intersection: " + intersection);
        
        Set<Integer> difference = new HashSet<>(setA);
        difference.removeAll(setB);
        System.out.println("Difference (A - B): " + difference);
    }

    // 3. Map Examples
    public static void mapExamples() {
        System.out.println("\n=== Map Examples ===");
        
        // HashMap
        Map<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Alice", 25);
        hashMap.put("Bob", 30);
        hashMap.put("Charlie", 35);
        hashMap.put("Alice", 26); // Update existing value
        
        System.out.println("HashMap: " + hashMap);
        System.out.println("Size: " + hashMap.size());
        System.out.println("Get Alice's age: " + hashMap.get("Alice"));
        
        // Check if key exists
        System.out.println("Contains key 'Bob': " + hashMap.containsKey("Bob"));
        System.out.println("Contains value 30: " + hashMap.containsValue(30));
        
        // Remove entry
        hashMap.remove("Charlie");
        System.out.println("After remove: " + hashMap);
        
        // Iterate through map
        System.out.println("Iterating through HashMap:");
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }
        
        // TreeMap (sorted by keys)
        Map<String, Integer> treeMap = new TreeMap<>();
        treeMap.put("Zebra", 10);
        treeMap.put("Apple", 20);
        treeMap.put("Banana", 30);
        treeMap.put("Cherry", 40);
        
        System.out.println("\nTreeMap: " + treeMap);
        System.out.println("First key: " + treeMap.firstKey());
        System.out.println("Last key: " + treeMap.lastKey());
        
        // LinkedHashMap (insertion order)
        Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("First", 1);
        linkedHashMap.put("Second", 2);
        linkedHashMap.put("Third", 3);
        
        System.out.println("\nLinkedHashMap: " + linkedHashMap);
        
        // Hashtable (thread-safe)
        Map<String, String> hashtable = new Hashtable<>();
        hashtable.put("Key1", "Value1");
        hashtable.put("Key2", "Value2");
        
        System.out.println("\nHashtable: " + hashtable);
        
        // Map operations
        Map<Integer, String> mapA = new HashMap<>();
        mapA.put(1, "One");
        mapA.put(2, "Two");
        mapA.put(3, "Three");
        
        Map<Integer, String> mapB = new HashMap<>();
        mapB.put(3, "Three");
        mapB.put(4, "Four");
        mapB.put(5, "Five");
        
        Map<Integer, String> combined = new HashMap<>(mapA);
        combined.putAll(mapB);
        System.out.println("\nCombined maps: " + combined);
    }

    // 4. Queue Examples
    public static void queueExamples() {
        System.out.println("\n=== Queue Examples ===");
        
        // LinkedList as Queue (FIFO)
        Queue<String> queue = new LinkedList<>();
        queue.add("First");
        queue.add("Second");
        queue.add("Third");
        
        System.out.println("Queue: " + queue);
        System.out.println("Front: " + queue.peek());
        System.out.println("Remove front: " + queue.poll());
        System.out.println("Queue after poll: " + queue);
        
        // PriorityQueue
        Queue<Integer> priorityQueue = new PriorityQueue<>();
        priorityQueue.add(30);
        priorityQueue.add(10);
        priorityQueue.add(50);
        priorityQueue.add(20);
        
        System.out.println("\nPriorityQueue: " + priorityQueue);
        while (!priorityQueue.isEmpty()) {
            System.out.print(priorityQueue.poll() + " ");
        }
        System.out.println();
        
        // ArrayDeque (double-ended queue)
        Deque<String> arrayDeque = new ArrayDeque<>();
        arrayDeque.addFirst("First");
        arrayDeque.addLast("Last");
        arrayDeque.add("Middle");
        
        System.out.println("\nArrayDeque: " + arrayDeque);
        System.out.println("First element: " + arrayDeque.getFirst());
        System.out.println("Last element: " + arrayDeque.getLast());
        
        // Stack operations (using ArrayDeque)
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        
        System.out.println("\nStack: " + stack);
        System.out.println("Pop: " + stack.pop());
        System.out.println("Stack after pop: " + stack);
    }

    // 5. Stream API Examples
    public static void streamExamples() {
        System.out.println("\n=== Stream API Examples ===");
        
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");
        
        // Filter and map
        List<String> filteredNames = names.stream()
            .filter(name -> name.startsWith("A"))
            .map(String::toUpperCase)
            .collect(Collectors.toList());
        
        System.out.println("Names starting with 'A' (uppercase): " + filteredNames);
        
        // Sort and limit
        List<String> sortedLimited = names.stream()
            .sorted()
            .limit(3)
            .collect(Collectors.toList());
        
        System.out.println("First 3 sorted names: " + sortedLimited);
        
        // Numeric operations
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        
        int sum = numbers.stream().mapToInt(Integer::intValue).sum();
        double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0);
        int max = numbers.stream().mapToInt(Integer::intValue).max().orElse(0);
        
        System.out.println("\nNumbers: " + numbers);
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + average);
        System.out.println("Max: " + max);
        
        // Grouping
        Map<Integer, List<String>> groupedByLength = names.stream()
            .collect(Collectors.groupingBy(String::length));
        
        System.out.println("\nNames grouped by length: " + groupedByLength);
        
        // Parallel stream
        List<Integer> squares = numbers.parallelStream()
            .map(n -> n * n)
            .collect(Collectors.toList());
        
        System.out.println("Squares (parallel): " + squares);
        
        // Reduce operation
        Optional<String> longestName = names.stream()
            .reduce((name1, name2) -> name1.length() > name2.length() ? name1 : name2);
        
        System.out.println("Longest name: " + longestName.orElse("No names"));
        
        // Flat map
        List<List<Integer>> nestedLists = Arrays.asList(
            Arrays.asList(1, 2, 3),
            Arrays.asList(4, 5, 6),
            Arrays.asList(7, 8, 9)
        );
        
        List<Integer> flattened = nestedLists.stream()
            .flatMap(List::stream)
            .collect(Collectors.toList());
        
        System.out.println("Flattened list: " + flattened);
    }
}

// Additional utility class for custom object examples
class Student implements Comparable<Student> {
    private String name;
    private int age;
    private double grade;
    
    public Student(String name, int age, double grade) {
        this.name = name;
        this.age = age;
        this.grade = grade;
    }
    
    public String getName() { return name; }
    public int getAge() { return age; }
    public double getGrade() { return grade; }
    
    @Override
    public String toString() {
        return String.format("%s (%d, %.1f)", name, age, grade);
    }
    
    @Override
    public int compareTo(Student other) {
        return this.name.compareTo(other.name);
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Student student = (Student) obj;
        return Objects.equals(name, student.name);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}

class StudentCollectionsDemo {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student("Alice", 20, 85.5),
            new Student("Bob", 22, 78.0),
            new Student("Charlie", 21, 92.3),
            new Student("David", 20, 88.7)
        );
        
        // Sort by name
        Collections.sort(students);
        System.out.println("Students sorted by name: " + students);
        
        // Sort by age using Comparator
        students.sort(Comparator.comparingInt(Student::getAge));
        System.out.println("Students sorted by age: " + students);
        
        // Filter high performers
        List<Student> highPerformers = students.stream()
            .filter(s -> s.getGrade() >= 85.0)
            .collect(Collectors.toList());
        
        System.out.println("High performers: " + highPerformers);
        
        // Group by age
        Map<Integer, List<Student>> byAge = students.stream()
            .collect(Collectors.groupingBy(Student::getAge));
        
        System.out.println("Students grouped by age: " + byAge);
    }
}

💻 Java Advanced Features java

🟡 intermediate ⭐⭐⭐⭐

Modern Java features including lambdas, streams, optional, and new language enhancements

⏱️ 35 min 🏷️ java, advanced, modern features
Prerequisites: Intermediate Java knowledge
// Java Advanced Features Examples

import java.util.*;
import java.util.function.*;
import java.util.stream.*;
import java.time.*;
import java.util.concurrent.*;
import java.nio.file.*;

public class JavaAdvancedFeatures {

    public static void main(String[] args) {
        lambdaExpressions();
        optionalExamples();
        streamApiAdvanced();
        dateAndTimeAPI();
        concurrentProgramming();
        pathAndFiles();
    }

    // 1. Lambda Expressions
    public static void lambdaExpressions() {
        System.out.println("=== Lambda Expressions ===");
        
        // Traditional vs Lambda
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
        
        // Traditional approach
        Collections.sort(names, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s1.compareTo(s2);
            }
        });
        
        // Lambda approach
        Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
        
        System.out.println("Sorted names: " + names);
        
        // Functional interfaces
        Predicate<String> startsWithA = s -> s.startsWith("A");
        Function<String, Integer> stringLength = String::length;
        Consumer<String> printer = System.out::println;
        Supplier<Double> randomSupplier = () -> Math.random();
        
        System.out.println("Names starting with 'A':");
        names.stream().filter(startsWithA).forEach(printer);
        
        System.out.println("Length of 'Hello': " + stringLength.apply("Hello"));
        System.out.println("Random number: " + randomSupplier.get());
        
        // Custom functional interface
        @FunctionalInterface
        interface MathOperation {
            int operate(int a, int b);
        }
        
        MathOperation addition = (a, b) -> a + b;
        MathOperation multiplication = (a, b) -> a * b;
        
        System.out.println("5 + 3 = " + addition.operate(5, 3));
        System.out.println("5 * 3 = " + multiplication.operate(5, 3));
        
        // Method references
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        // Static method reference
        numbers.stream().map(Math::abs).forEach(System.out::print);
        System.out.println();
        
        // Instance method reference
        names.stream().map(String::toUpperCase).forEach(System.out::println);
    }

    // 2. Optional Examples
    public static void optionalExamples() {
        System.out.println("\n=== Optional Examples ===");
        
        // Creating Optionals
        Optional<String> nonEmptyOptional = Optional.of("Hello");
        Optional<String> emptyOptional = Optional.empty();
        Optional<String> nullableOptional = Optional.ofNullable(null);
        
        System.out.println("Non-empty: " + nonEmptyOptional.orElse("Default"));
        System.out.println("Empty: " + emptyOptional.orElse("Default"));
        System.out.println("Nullable: " + nullableOptional.orElse("Default"));
        
        // Optional methods
        Optional<String> optional = Optional.of("Java 8 Features");
        
        // ifPresent
        optional.ifPresent(value -> System.out.println("Value: " + value));
        
        // map and flatMap
        Optional<Integer> length = optional.map(String::length);
        System.out.println("Length: " + length.orElse(0));
        
        // filter
        Optional<String> filtered = optional.filter(s -> s.startsWith("Java"));
        System.out.println("Filtered: " + filtered.orElse("No match"));
        
        // orElse and orElseGet
        String result1 = nullableOptional.orElse("Default value");
        String result2 = nullableOptional.orElseGet(() -> "Generated default");
        
        System.out.println("Result 1: " + result1);
        System.out.println("Result 2: " + result2);
        
        // orElseThrow
        try {
            String value = nullableOptional.orElseThrow(() -> new IllegalArgumentException("Value not found"));
            System.out.println("Value: " + value);
        } catch (Exception e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
        
        // Nested Optional processing
        class User {
            private Optional<Address> address;
            public User(Optional<Address> address) { this.address = address; }
            public Optional<Address> getAddress() { return address; }
        }
        
        class Address {
            private String city;
            public Address(String city) { this.city = city; }
            public String getCity() { return city; }
        }
        
        Optional<User> user = Optional.of(new User(Optional.of(new Address("New York"))));
        
        // Nested Optional handling
        String city = user.flatMap(User::getAddress)
                          .map(Address::getCity)
                          .orElse("Unknown");
        
        System.out.println("User city: " + city);
    }

    // 3. Advanced Stream API
    public static void streamApiAdvanced() {
        System.out.println("\n=== Advanced Stream API ===");
        
        List<Person> people = Arrays.asList(
            new Person("Alice", 25, "New York"),
            new Person("Bob", 30, "London"),
            new Person("Charlie", 35, "Paris"),
            new Person("David", 28, "New York"),
            new Person("Eve", 32, "Tokyo")
        );
        
        // Complex filtering and mapping
        Map<String, List<String>> namesByCity = people.stream()
            .filter(p -> p.getAge() > 25)
            .collect(Collectors.groupingBy(
                Person::getCity,
                Collectors.mapping(Person::getName, Collectors.toList())
            ));
        
        System.out.println("People over 25 grouped by city: " + namesByCity);
        
        // Partitioning
        Map<Boolean, List<Person>> partitionedByAge = people.stream()
            .collect(Collectors.partitioningBy(p -> p.getAge() > 30));
        
        System.out.println("Partitioned by age > 30: " + partitionedByAge);
        
        // Multi-level grouping
        Map<String, Map<Integer, List<Person>>> multiLevelGrouping = people.stream()
            .collect(Collectors.groupingBy(
                Person::getCity,
                Collectors.groupingBy(Person::getAge)
            ));
        
        System.out.println("Multi-level grouping by city and age: " + multiLevelGrouping);
        
        // Parallel stream with custom collector
        String concatenatedNames = people.parallelStream()
            .map(Person::getName)
            .collect(Collector.of(
                StringBuilder::new,
                (sb, name) -> sb.append(name).append(", "),
                StringBuilder::append,
                StringBuilder::toString
            ));
        
        System.out.println("Concatenated names: " + concatenatedNames);
        
        // Statistics
        IntSummaryStatistics ageStats = people.stream()
            .mapToInt(Person::getAge)
            .summaryStatistics();
        
        System.out.println("Age statistics: " + ageStats);
        
        // Custom reduction
        String namesJoined = people.stream()
            .map(Person::getName)
            .reduce("", (a, b) -> a + (a.isEmpty() ? "" : ", ") + b);
        
        System.out.println("Names joined: " + namesJoined);
    }

    // 4. Date and Time API
    public static void dateAndTimeAPI() {
        System.out.println("\n=== Date and Time API ===");
        
        // Current date and time
        LocalDateTime now = LocalDateTime.now();
        System.out.println("Current date and time: " + now);
        
        // Creating specific dates
        LocalDate date1 = LocalDate.of(2024, 1, 15);
        LocalTime time1 = LocalTime.of(14, 30, 45);
        LocalDateTime dateTime1 = LocalDateTime.of(date1, time1);
        
        System.out.println("Specific date: " + date1);
        System.out.println("Specific time: " + time1);
        System.out.println("Specific datetime: " + dateTime1);
        
        // Parsing and formatting
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatted = now.format(formatter);
        LocalDateTime parsed = LocalDateTime.parse(formatted, formatter);
        
        System.out.println("Formatted: " + formatted);
        System.out.println("Parsed: " + parsed);
        
        // Date manipulation
        LocalDate tomorrow = now.plusDays(1).toLocalDate();
        LocalDate lastWeek = now.minusWeeks(1).toLocalDate();
        
        System.out.println("Tomorrow: " + tomorrow);
        System.out.println("Last week: " + lastWeek);
        
        // Period and Duration
        Period period = Period.between(date1, now.toLocalDate());
        Duration duration = Duration.between(time1, now.toLocalTime());
        
        System.out.println("Period between dates: " + period);
        System.out.println("Duration between times: " + duration);
        
        // Temporal adjusters
        LocalDate nextMonday = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        LocalDate lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
        
        System.out.println("Next Monday: " + nextMonday);
        System.out.println("Last day of month: " + lastDayOfMonth);
        
        // Zone handling
        ZonedDateTime zonedNow = ZonedDateTime.now(ZoneId.of("America/New_York"));
        System.out.println("New York time: " + zonedNow);
        
        // Instant (UTC timestamp)
        Instant instant = Instant.now();
        System.out.println("UTC timestamp: " + instant);
    }

    // 5. Concurrent Programming
    public static void concurrentProgramming() {
        System.out.println("\n=== Concurrent Programming ===");
        
        // ExecutorService
        ExecutorService executor = Executors.newFixedThreadPool(3);
        
        List<Future<String>> futures = new ArrayList<>();
        
        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            Future<String> future = executor.submit(() -> {
                Thread.sleep(1000);
                return "Task " + taskId + " completed";
            });
            futures.add(future);
        }
        
        // Collect results
        for (Future<String> future : futures) {
            try {
                System.out.println(future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        
        executor.shutdown();
        
        // CompletableFuture
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello";
        }).thenApply(result -> result + " World")
          .thenApply(result -> result + "!")
          .exceptionally(ex -> "Fallback result");
        
        try {
            System.out.println("CompletableFuture result: " + completableFuture.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        
        // Parallel Stream
        List<Integer> numbers = IntStream.range(1, 10001).boxed().collect(Collectors.toList());
        
        long startTime = System.currentTimeMillis();
        long sum = numbers.parallelStream().mapToLong(Integer::longValue).sum();
        long endTime = System.currentTimeMillis();
        
        System.out.println("Parallel sum: " + sum);
        System.out.println("Time taken: " + (endTime - startTime) + "ms");
    }

    // 6. Path and Files API
    public static void pathAndFiles() {
        System.out.println("\n=== Path and Files API ===");
        
        // Path operations
        Path path = Paths.get("src", "main", "java", "Test.java");
        System.out.println("Path: " + path);
        System.out.println("File name: " + path.getFileName());
        System.out.println("Parent: " + path.getParent());
        System.out.println("Root: " + path.getRoot());
        
        // File operations
        try {
            // Create directory
            Path tempDir = Files.createTempDirectory("test");
            System.out.println("Created temp directory: " + tempDir);
            
            // Create file
            Path tempFile = Files.createTempFile(tempDir, "test", ".txt");
            System.out.println("Created temp file: " + tempFile);
            
            // Write to file
            String content = "Hello, Files API!\nThis is a test file.";
            Files.write(tempFile, content.getBytes(), StandardOpenOption.WRITE);
            
            // Read from file
            String readContent = new String(Files.readAllBytes(tempFile));
            System.out.println("File content: " + readContent);
            
            // File attributes
            BasicFileAttributes attrs = Files.readAttributes(tempFile, BasicFileAttributes.class);
            System.out.println("File size: " + attrs.size() + " bytes");
            System.out.println("Created: " + attrs.creationTime());
            System.out.println("Last modified: " + attrs.lastModifiedTime());
            
            // List directory contents
            System.out.println("Directory contents:");
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(tempDir)) {
                for (Path entry : stream) {
                    System.out.println("  " + entry.getFileName());
                }
            }
            
            // Clean up
            Files.delete(tempFile);
            Files.delete(tempDir);
            System.out.println("Cleaned up temp files");
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // File walking
        try {
            Path currentDir = Paths.get(".");
            System.out.println("\nWalking directory tree:");
            
            Files.walk(currentDir)
                .filter(Files::isRegularFile)
                .limit(10) // Limit to first 10 files
                .forEach(file -> System.out.println("  " + file));
                
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// Supporting class for stream examples
class Person {
    private String name;
    private int age;
    private String city;
    
    public Person(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
    
    public String getName() { return name; }
    public int getAge() { return age; }
    public String getCity() { return city; }
    
    @Override
    public String toString() {
        return String.format("%s (%d, %s)", name, age, city);
    }
}