#java

93 snippets tagged with #java

javabeginner

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

#java#string
javabeginner

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

#java#file-io
javabeginner

HashMap Operations and Patterns

Essential HashMap operations: put, get, merge, compute, getOrDefault, and iteration patterns.

Best for: Counting word frequencies in text

#java#collections
javabeginner

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#streams
javabeginner

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#optional
javaintermediate

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

#java#http
javaintermediate

CompletableFuture — Async Programming

Chain async operations with CompletableFuture: thenApply, thenCompose, allOf, and exception handling.

Best for: Parallel API calls to multiple services

#java#async
javabeginner

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

#java#records
javaintermediate

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

#java#sealed-classes
javaadvanced

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

#java#virtual-threads
javaintermediate

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#rest-api
javaintermediate

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

#spring-boot#error-handling
javaintermediate

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

#jpa#spring-data
javaintermediate

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

#spring-data#jpa
javaintermediate

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

#java#design-patterns
javaintermediate

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

#java#design-patterns
javaintermediate

Strategy Pattern with Lambdas

Implement the Strategy pattern using interfaces and Java lambdas for flexible algorithm selection.

Best for: Swappable pricing or discount algorithms

#java#design-patterns
javaintermediate

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

#java#design-patterns
javaintermediate

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

#java#design-patterns
javaintermediate

ExecutorService — Thread Pool Management

Create and manage thread pools with ExecutorService: fixed, cached, scheduled, and custom pools.

Best for: Managing concurrent task execution

#java#concurrency
javaadvanced

Concurrent Collections — Thread-Safe Maps

Use ConcurrentHashMap, CopyOnWriteArrayList, and BlockingQueue for thread-safe data structures.

Best for: Thread-safe caching in multi-threaded applications

#java#concurrency
javaintermediate

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

#java#junit
javaintermediate

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#mockito
javabeginner

Java Date/Time API — Modern Operations

Work with LocalDate, LocalDateTime, ZonedDateTime, Duration, Period, and date formatting.

Best for: Date arithmetic and business day calculations

#java#date-time
javaintermediate

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

#java#json
javaadvanced

Advanced Streams — Custom Collectors

Advanced Stream operations: custom collectors, flatMap, reduce, teeing, and parallel streams.

Best for: Complex data aggregation and reporting

#java#streams
javabeginner

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

#java#switch
javabeginner

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

#java#text-blocks
javaadvanced

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#jwt
javaintermediate

Spring Boot — Custom Validator Annotation

Create custom validation annotations with ConstraintValidator for domain-specific field validation.

Best for: Domain-specific input validation

#spring-boot#validation
javaadvanced

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

#spring-boot#webflux
javabeginner

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#resource-management
javaadvanced

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#generics
javaintermediate

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#enums
javaintermediate

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

#java#regex
javaadvanced

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#encryption
javabeginner

Java List Operations and Utilities

Essential List operations: create, sort, search, transform, partition, and immutable list patterns.

Best for: Common list manipulation patterns

#java#collections
javaintermediate

Custom Exception Hierarchy

Design a clean exception hierarchy with custom exceptions, error codes, and exception mapping.

Best for: Consistent error handling across services

#java#exceptions
javaintermediate

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#functional
javabeginner

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

#java#logging
javabeginner

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

#java#csv
javaintermediate

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

#java#retry
javaadvanced

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#rate-limiting
javaintermediate

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#process
javaintermediate

Java File Watcher — Directory Monitoring

Watch directories for file changes using WatchService: create, modify, delete events with filtering.

Best for: Auto-reloading configuration files

#java#file-watcher
javabeginner

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

#java#zip
javaadvanced

Custom Annotations and Reflection

Create and process custom annotations with reflection: field validation, auto-logging, and metadata.

Best for: Custom validation frameworks

#java#annotations
javaintermediate

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

#java#http
javabeginner

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

#java#sorting
javaadvanced

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

#java#parallel
javabeginner

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#method-reference
javaintermediate

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#map
javaadvanced

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#reactive
javaadvanced

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

#java#proxy
javaintermediate

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

#java#decorator
javaintermediate

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

#java#events
javaadvanced

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

#java#cache
javaintermediate

Immutable Classes and Defensive Copies

Create truly immutable Java classes with defensive copies, unmodifiable collections, and builder pattern.

Best for: Thread-safe domain objects

#java#immutability
javabeginner

Pattern Matching for instanceof

Use modern Java pattern matching with instanceof, guarded patterns, and record deconstruction.

Best for: Type-safe polymorphic processing

#java#pattern-matching
javabeginner

Java String Formatting and Templates

String formatting techniques: printf, format, MessageFormat, StringJoiner, and text block interpolation.

Best for: Formatted log messages and reports

#java#string
javabeginner

Environment Configuration Management

Load configuration from environment variables, properties files, and system properties with defaults.

Best for: Application configuration management

#java#configuration
javaadvanced

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

#java#circuit-breaker
javaadvanced

Connection Pool Implementation

Build a generic connection pool with size limits, idle timeout, health checks, and metrics.

Best for: Database connection pooling

#java#connection-pool
javaintermediate

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

#java#json
javaintermediate

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

#java#cli
javaadvanced

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

#java#threadlocal
javaintermediate

BlockingQueue — Producer Consumer Pattern

Implement producer-consumer with BlockingQueue: bounded buffers, multiple producers, and graceful shutdown.

Best for: Task queue processing systems

#java#concurrency
javaintermediate

Secure Password Hashing

Hash passwords securely with PBKDF2 and verify them — no external libraries required.

Best for: User registration password storage

#java#security
javaintermediate

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

#java#records
javaadvanced

Structured Concurrency (Java 21+)

Use StructuredTaskScope for parallel subtasks with automatic cancellation and error propagation.

Best for: Parallel API aggregation with auto-cancellation

#java#concurrency
javaadvanced

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

#spring-boot#aop
javaintermediate

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

#java#iterator
javaadvanced

Manual Dependency Injection Container

Build a simple DI container with constructor injection, singleton scope, and interface binding.

Best for: Understanding dependency injection internals

#java#dependency-injection
javaintermediate

Stream MapReduce and Aggregation

Use streams for MapReduce-style operations: reduce, collect, summarize, and complex aggregations.

Best for: Sales data aggregation and reporting

#java#streams
javaintermediate

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

#java#tree
javaadvanced

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

#java#graph
javaadvanced

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

#java#reflection
javabeginner

Varargs and Method Overloading

Use varargs for flexible APIs: method overloading, safe varargs, and patterns for builder methods.

Best for: Flexible API method signatures

#java#varargs
javaadvanced

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

#java#sorting
javaintermediate

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

#java#collections
javaintermediate

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

#java#object-pool
javaintermediate

Semaphore — Concurrency Control

Control concurrent access with Semaphore: rate limiting, resource pools, and bounded parallelism.

Best for: Limiting concurrent API calls to external services

#java#semaphore
javaadvanced

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

#java#references
javaadvanced

Fork/Join Framework — Divide and Conquer

Parallelize recursive tasks with ForkJoinPool: RecursiveTask, RecursiveAction, and work-stealing.

Best for: CPU-intensive divide-and-conquer algorithms

#java#fork-join
javaadvanced

CompletableFuture Combinators — allOf, anyOf, compose

Compose async operations with CompletableFuture: allOf, anyOf, thenCombine, handle, and timeout.

Best for: Aggregating results from multiple microservices

#java#async
javaintermediate

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

#java#exceptions
javabeginner

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

#java#configuration
javaintermediate

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

#java#health-check
javaadvanced

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

#java#builder
javaintermediate

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

#java#string
javaadvanced

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

#java#virtual-threads
javaintermediate

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#binary-search
scalabeginner

Java Interop and Collections

Work with Java libraries from Scala: collection conversions, null safety, and API wrapping.

Best for: Using Java libraries from Scala

#scala#java