#java
93 snippets tagged with #java
Reverse a String in Java
Multiple ways to reverse a string in Java including StringBuilder, char array, and stream approaches.
Best for: String manipulation in coding interviews
Read File Line by Line in Java
Read files using BufferedReader, Files.readAllLines, and Stream API with proper resource management.
Best for: Processing log files line by line
HashMap Operations and Patterns
Essential HashMap operations: put, get, merge, compute, getOrDefault, and iteration patterns.
Best for: Counting word frequencies in text
Java Streams — Filter, Map, Collect
Process collections with Java Streams: filter, map, flatMap, reduce, and collect to lists or maps.
Best for: Transforming and filtering collections
Java Optional — Avoid NullPointerException
Use Optional to handle nullable values safely with map, flatMap, orElse, and ifPresent patterns.
Best for: Eliminating NullPointerException in business logic
Java HttpClient — GET and POST Requests
Make HTTP requests with Java 11+ HttpClient: GET, POST JSON, async calls, and response handling.
Best for: Calling REST APIs from Java applications
CompletableFuture — Async Programming
Chain async operations with CompletableFuture: thenApply, thenCompose, allOf, and exception handling.
Best for: Parallel API calls to multiple services
Java Records — Immutable Data Classes
Use Java records for concise immutable data carriers with built-in equals, hashCode, and toString.
Best for: Replacing verbose POJO classes with concise records
Sealed Classes and Pattern Matching
Use sealed interfaces with pattern matching switch for type-safe, exhaustive algebraic data types.
Best for: Type-safe state machines and event handling
Virtual Threads — Lightweight Concurrency
Use Java 21 virtual threads for massive concurrency without thread pool tuning or reactive frameworks.
Best for: High-concurrency web servers handling thousands of requests
Spring Boot REST Controller with CRUD
Create a complete REST API with Spring Boot: GET, POST, PUT, DELETE with validation and error handling.
Best for: Building RESTful APIs with Spring Boot
Spring Boot Global Exception Handler
Centralized error handling with @ControllerAdvice for validation errors, 404s, and custom exceptions.
Best for: Consistent error responses across all endpoints
JPA Entity Mapping with Relationships
Map entities with JPA annotations: OneToMany, ManyToOne, ManyToMany with fetch strategies and cascading.
Best for: Database schema design with JPA entities
Spring Data JPA — Custom Queries
Write custom JPA queries with @Query, derived methods, Specifications, and native SQL for complex lookups.
Best for: Complex database queries in Spring applications
Builder Pattern — Fluent Object Construction
Implement the Builder pattern for complex objects with validation, immutability, and method chaining.
Best for: Constructing complex objects with many optional parameters
Singleton Pattern — Thread-Safe Approaches
Implement thread-safe singletons in Java: enum, holder class, double-checked locking, and eager init.
Best for: Application-wide configuration managers
Strategy Pattern with Lambdas
Implement the Strategy pattern using interfaces and Java lambdas for flexible algorithm selection.
Best for: Swappable pricing or discount algorithms
Factory Method Pattern with Registry
Implement the Factory pattern using a registry map for extensible object creation without switch statements.
Best for: Extensible object creation in plugin architectures
Observer Pattern — Event System
Build a type-safe event system using the Observer pattern with generics and functional interfaces.
Best for: Decoupled event-driven architectures
ExecutorService — Thread Pool Management
Create and manage thread pools with ExecutorService: fixed, cached, scheduled, and custom pools.
Best for: Managing concurrent task execution
Concurrent Collections — Thread-Safe Maps
Use ConcurrentHashMap, CopyOnWriteArrayList, and BlockingQueue for thread-safe data structures.
Best for: Thread-safe caching in multi-threaded applications
JUnit 5 — Test Patterns and Assertions
Write JUnit 5 tests with assertions, lifecycle hooks, nested tests, parameterized tests, and dynamic tests.
Best for: Unit testing Java applications with JUnit 5
Mockito — Mocking and Verification
Mock dependencies with Mockito: when/thenReturn, verify, argument captors, and spy patterns.
Best for: Testing service layers with mocked dependencies
Java Date/Time API — Modern Operations
Work with LocalDate, LocalDateTime, ZonedDateTime, Duration, Period, and date formatting.
Best for: Date arithmetic and business day calculations
Jackson — JSON Serialization and Parsing
Parse and generate JSON with Jackson: ObjectMapper, annotations, custom serializers, and streaming.
Best for: REST API request and response serialization
Advanced Streams — Custom Collectors
Advanced Stream operations: custom collectors, flatMap, reduce, teeing, and parallel streams.
Best for: Complex data aggregation and reporting
Switch Expressions — Modern Java
Use switch expressions with arrow syntax, pattern matching, guards, and yield for concise branching.
Best for: Concise branching logic replacing verbose if-else
Text Blocks — Multi-line Strings
Use Java text blocks for readable multi-line strings: SQL, JSON, HTML, and formatted templates.
Best for: Embedding SQL queries in Java code
Spring Security — JWT Authentication
Implement JWT authentication with Spring Security: token generation, validation, and filter chain.
Best for: Securing REST APIs with JWT tokens
Spring Boot — Custom Validator Annotation
Create custom validation annotations with ConstraintValidator for domain-specific field validation.
Best for: Domain-specific input validation
Spring WebFlux — Reactive REST API
Build reactive REST APIs with Spring WebFlux using Mono, Flux, and non-blocking operations.
Best for: High-throughput non-blocking APIs
Try-With-Resources and AutoCloseable
Manage resources safely with try-with-resources: files, connections, streams, and custom resources.
Best for: Safe resource management preventing leaks
Java Generics — Bounded Types and Wildcards
Master Java generics: bounded types, wildcards, generic methods, and type-safe collection utilities.
Best for: Type-safe generic utility methods and classes
Java Enums — Methods, Fields, and Interfaces
Advanced enum patterns: enums with fields, abstract methods, implementing interfaces, and enum maps.
Best for: Type-safe constants with behavior
Java Regex — Pattern Matching Examples
Common regex patterns with Pattern and Matcher: email, URL, phone, extraction, and replacement.
Best for: Input validation for emails, URLs, and phone numbers
AES Encryption and Decryption
Encrypt and decrypt data with AES-GCM in Java: key generation, secure random IV, and Base64 encoding.
Best for: Encrypting sensitive data at rest
Java List Operations and Utilities
Essential List operations: create, sort, search, transform, partition, and immutable list patterns.
Best for: Common list manipulation patterns
Custom Exception Hierarchy
Design a clean exception hierarchy with custom exceptions, error codes, and exception mapping.
Best for: Consistent error handling across services
Functional Interfaces and Lambda Patterns
Use built-in and custom functional interfaces: Predicate, Function, Consumer, Supplier, and composition.
Best for: Composable validation and filtering logic
Java Logging with SLF4J and Logback
Configure structured logging with SLF4J: log levels, MDC context, JSON format, and best practices.
Best for: Application logging with contextual information
CSV Parser — Read and Write CSV Files
Parse and write CSV files in Java without external libraries using BufferedReader and String operations.
Best for: Parsing CSV data files without external libraries
Retry Mechanism with Exponential Backoff
Implement retries with exponential backoff, jitter, max attempts, and exception-specific handling.
Best for: Resilient API calls with transient failure handling
Rate Limiter — Token Bucket Algorithm
Implement a thread-safe rate limiter using the token bucket algorithm for API throttling.
Best for: API rate limiting per user or IP
Java ProcessBuilder — Execute System Commands
Run external processes from Java: capture output, handle errors, timeouts, and piped commands.
Best for: Running system commands from Java applications
Java File Watcher — Directory Monitoring
Watch directories for file changes using WatchService: create, modify, delete events with filtering.
Best for: Auto-reloading configuration files
ZIP Compression and Extraction
Compress and extract ZIP archives in Java using ZipOutputStream and ZipInputStream with directory support.
Best for: Creating ZIP archives for file downloads
Custom Annotations and Reflection
Create and process custom annotations with reflection: field validation, auto-logging, and metadata.
Best for: Custom validation frameworks
Java Built-in HTTP Server
Create a lightweight HTTP server with com.sun.net.httpserver: routing, JSON responses, file serving.
Best for: Lightweight HTTP servers for testing and prototyping
Comparator Chains — Multi-Field Sorting
Sort objects by multiple fields using Comparator.comparing, thenComparing, and custom comparators.
Best for: Multi-field sorting for display and reporting
Parallel Stream Processing
Use parallel streams for CPU-intensive tasks: when to use, performance tips, and thread-safety.
Best for: CPU-intensive data processing with multi-core utilization
Method References — All Four Types
Use method references for concise lambda expressions: static, instance, arbitrary object, and constructor.
Best for: Concise functional-style code with method references
Java Map — Advanced Operations
Master Map operations: compute, merge, getOrDefault, multi-map, BiMap, and stream-based grouping.
Best for: Aggregation and grouping operations on data
Java Flow API — Reactive Streams
Implement reactive publishers and subscribers with Java Flow API: backpressure, buffering, and transformation.
Best for: Reactive data processing with backpressure
Java Dynamic Proxy Pattern
Create dynamic proxies for cross-cutting concerns: logging, caching, transaction management, and metrics.
Best for: AOP-style cross-cutting concern handling
Decorator Pattern — OOP and Functional
Implement the decorator pattern both classically and with functional composition for flexible behavior.
Best for: Adding behavior to objects without subclassing
In-Memory Event Bus — Pub/Sub Pattern
Build a type-safe in-memory event bus with subscribe, publish, and async event delivery.
Best for: Decoupled event-driven architectures
LRU Cache — Thread-Safe Implementation
Implement a thread-safe LRU cache with configurable size, TTL expiry, and statistics tracking.
Best for: Application-level caching without external systems
Immutable Classes and Defensive Copies
Create truly immutable Java classes with defensive copies, unmodifiable collections, and builder pattern.
Best for: Thread-safe domain objects
Pattern Matching for instanceof
Use modern Java pattern matching with instanceof, guarded patterns, and record deconstruction.
Best for: Type-safe polymorphic processing
Java String Formatting and Templates
String formatting techniques: printf, format, MessageFormat, StringJoiner, and text block interpolation.
Best for: Formatted log messages and reports
Environment Configuration Management
Load configuration from environment variables, properties files, and system properties with defaults.
Best for: Application configuration management
Circuit Breaker Pattern
Implement a circuit breaker with states (closed, open, half-open), failure counting, and auto-recovery.
Best for: Protecting services from cascading failures
Connection Pool Implementation
Build a generic connection pool with size limits, idle timeout, health checks, and metrics.
Best for: Database connection pooling
JSON Serialization Without Libraries
Serialize and deserialize Java objects to JSON manually with a lightweight builder-based approach.
Best for: Lightweight JSON generation without Jackson/Gson
CLI Argument Parser
Parse command-line arguments with flags, options, positional args, and help text without external libraries.
Best for: Command-line tool argument parsing
ThreadLocal and Scoped Values
Use ThreadLocal for per-thread data and ScopedValue (Java 21+) for structured concurrency contexts.
Best for: Request-scoped context in web servers
BlockingQueue — Producer Consumer Pattern
Implement producer-consumer with BlockingQueue: bounded buffers, multiple producers, and graceful shutdown.
Best for: Task queue processing systems
Secure Password Hashing
Hash passwords securely with PBKDF2 and verify them — no external libraries required.
Best for: User registration password storage
Records and Sealed Types — ADT Modeling
Model algebraic data types with records and sealed interfaces for type-safe domain modeling.
Best for: Type-safe error handling with Result type
Structured Concurrency (Java 21+)
Use StructuredTaskScope for parallel subtasks with automatic cancellation and error propagation.
Best for: Parallel API aggregation with auto-cancellation
Spring Boot AOP — Aspects and Advice
Use Spring AOP for cross-cutting concerns: logging, timing, auditing, and transaction-like behavior.
Best for: Automatic method logging across services
Custom Iterator and Iterable
Implement custom iterators and iterables for specialized data traversal and lazy sequence generation.
Best for: Lazy sequence generation for large datasets
Manual Dependency Injection Container
Build a simple DI container with constructor injection, singleton scope, and interface binding.
Best for: Understanding dependency injection internals
Stream MapReduce and Aggregation
Use streams for MapReduce-style operations: reduce, collect, summarize, and complex aggregations.
Best for: Sales data aggregation and reporting
Tree Traversal — DFS and BFS
Implement tree data structure with DFS (pre/in/post order), BFS, and recursive/iterative traversals.
Best for: Tree-based data structure traversal
Graph — Dijkstra Shortest Path
Implement Dijkstra's shortest path algorithm with adjacency list, priority queue, and path reconstruction.
Best for: Shortest path finding in weighted graphs
Reflection Utilities — Inspect and Invoke
Inspect classes at runtime: list fields/methods, invoke methods, get annotations, and create instances.
Best for: Framework and library development
Varargs and Method Overloading
Use varargs for flexible APIs: method overloading, safe varargs, and patterns for builder methods.
Best for: Flexible API method signatures
Sorting Algorithms — Quick, Merge, and Heap
Implement classic sorting algorithms in Java: quicksort, mergesort, heapsort, and their time complexity.
Best for: Understanding sorting algorithm trade-offs
MultiMap and BiMap Implementations
Implement MultiMap and BiMap data structures for one-to-many and bidirectional key-value mappings.
Best for: Tag/category systems with multiple values per key
Object Pool Pattern
Reuse expensive objects with an object pool: thread-safe checkout, return, health validation, and eviction.
Best for: Reusing expensive-to-create objects
Semaphore — Concurrency Control
Control concurrent access with Semaphore: rate limiting, resource pools, and bounded parallelism.
Best for: Limiting concurrent API calls to external services
Weak, Soft, and Phantom References
Use Java reference types for memory-efficient caches, resource cleanup, and GC-aware data structures.
Best for: Memory-sensitive caching that adapts to JVM pressure
Fork/Join Framework — Divide and Conquer
Parallelize recursive tasks with ForkJoinPool: RecursiveTask, RecursiveAction, and work-stealing.
Best for: CPU-intensive divide-and-conquer algorithms
CompletableFuture Combinators — allOf, anyOf, compose
Compose async operations with CompletableFuture: allOf, anyOf, thenCombine, handle, and timeout.
Best for: Aggregating results from multiple microservices
Checked Exception Wrapping Utilities
Wrap checked exceptions for use in lambdas and streams: sneaky throws, functional wrappers, and Either.
Best for: Using checked-exception methods in lambda expressions
Properties and Config File Loader
Load configuration from .properties files, system env, and defaults with a type-safe config class.
Best for: Application configuration with environment overrides
Health Check — Liveness and Readiness
Implement health check endpoints for liveness and readiness probes with dependency status reporting.
Best for: Kubernetes liveness and readiness probes
Type-Safe Step Builder Pattern
Enforce required fields at compile time with a step builder: each step returns the next interface.
Best for: Enforcing required fields at compile time
String Pool and Interning
Understand Java string pooling: intern(), identity vs equality, memory optimization, and common pitfalls.
Best for: Memory optimization for repeated string values
Virtual Threads — Practical Patterns
Use Java 21 virtual threads for high-concurrency I/O: per-request threads, structured scopes, and limits.
Best for: High-concurrency I/O-bound servers
Binary Search — Lower Bound, Upper Bound, and Rotated Array
Binary search variants: lower/upper bound, search in rotated sorted array, and finding peaks.
Best for: Efficient search in sorted datasets
Java Interop and Collections
Work with Java libraries from Scala: collection conversions, null safety, and API wrapping.
Best for: Using Java libraries from Scala