Category Archives: Java

Understanding LinkedHashMap in Java

Let’s dive into a fascinating corner of Java’s Collections Framework: the LinkedHashMap. You might already be familiar with HashMap for its speedy key-value pair storage and LinkedHashSet for maintaining insertion order in a set. Well, LinkedHashMap is the best of both worlds, offering the familiar map interface with the added benefit of predictable iteration order.

Let’s break down what makes LinkedHashMap so special and when you should consider using it.

What is LinkedHashMap?

In simple terms, LinkedHashMap is a hash table and a linked list implementation of the Map interface. It inherits all the goodness from HashMap (fast lookups, insertions, and deletions) but adds an internal doubly-linked list that runs through all of its entries. This linked list defines the iteration order, which can either be:

  1. Insertion Order: The default behavior, where elements are iterated in the order they were first inserted into the map.
  2. Access Order: Elements are iterated in the order they were last accessed (read or written). This is particularly useful for implementing LRU (Least Recently Used) caches.

Like HashMapLinkedHashMap allows one null key and multiple null values.

Interface Hierarchy

LinkedHashMap implements the following interfaces and extends the following class:

  • java.io.Serializable
  • java.util.Map
  • java.lang.Cloneable

And it extends java.util.HashMap.

Continue reading Understanding LinkedHashMap in Java

Using Regular Expressions with Java 8 Predicates for Clean Code

Java 8 introduced some powerful functional interfaces, and one of the most versatile is Predicate. A Predicate represents a boolean-valued function of one argument. While it’s commonly used for simple checks, combining it with regular expressions opens up a world of possibilities for more complex data validation and filtering, all within a concise and readable lambda expression.

In this post, we’ll explore how to leverage Java’s Pattern.compile() method to create efficient and reusable regex-based predicates. This approach is particularly useful when you need to perform the same regex validation multiple times, avoiding recompilation overhead for each check.

The Problem with Repeated Regex Matching

Let’s say you have a list of strings, and you want to filter them based on whether they match a specific regular expression. A naive approach might look something like this:

Continue reading Using Regular Expressions with Java 8 Predicates for Clean Code

Lombok @Builder: The Definitive Guide to Clean and Fluent Object Creation

As Java applications grow, creating and initializing objects can become a cumbersome task. We’ve all seen them: constructors with a long list of parameters, some of which are optional, leading to multiple overloaded constructors or the error-prone “telescoping constructor” anti-pattern. The traditional solution is the Builder design pattern, which provides a readable, fluent API for object creation. However, writing a Builder by hand for every DTO or entity is tedious and adds significant boilerplate code to your project.

This is where Project Lombok’s @Builder annotation comes to the rescue. It automatically generates the complete, robust Builder pattern implementation for your class at compile time, leaving your source code clean, concise, and focused on its primary responsibility.

In this guide, we’ll dive deep into @Builder, from basic setup to its most powerful and advanced features.

1. Why Do We Need a Builder?

Let’s consider a simple Employee class. Without a builder, you might initialize it like this:


// Telescoping constructors - hard to read, easy to make mistakes
Employee emp1 = new Employee(1L, "Ankur", "Kumar", "DEV", "ACTIVE");
Employee emp2 = new Employee(2L, "John", "Doe", "QA"); // What is the default status?

Continue reading Lombok @Builder: The Definitive Guide to Clean and Fluent Object Creation

Building Your First Spring RESTful API: A “Hello World” Guide

Let’s dive into the exciting world of Spring Boot and RESTful APIs. If you’re looking to build robust, scalable web services, Spring Boot is an excellent choice and understanding how to create a simple REST API is a fundamental first step.

In this tutorial, we’ll walk through creating a “Hello World” RESTful service that exposes JSON data. This example will cover the basic setup of a Spring Boot project and demonstrating how to handle HTTP GET requests.

Prerequisites

Before we begin, make sure you have the following installed:

  • Java Development Kit (JDK) 8 or higher: You can download it from the Oracle website.
  • Apache Maven: For project management and dependency handling. Download from the Maven website.
  • An Integrated Development Environment (IDE): IntelliJ IDEA, Eclipse, or VS Code with Java extensions are all great choices.

Step 1: Create a Spring Boot Project

The easiest way to start a Spring Boot project is by using the Spring Initializr. Go to the website and configure your project as follows:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Choose the latest stable version (e.g., 2.7.x or 3.x.x)
  • Group: com.ankurm.restapi
  • Artifact: hello-world
  • Name: hello-world
  • Package name: com.ankurm.restapi.helloworld
  • Packaging: Jar
  • Java: 17 (or your preferred version)
  • Dependencies: Add Spring Web

Click “Generate” to download the project as a ZIP file. Extract it to your desired location.

Continue reading Building Your First Spring RESTful API: A “Hello World” Guide

From Raw Threads to Virtual Threads: A Developer’s Guide to Java Concurrency

If you’ve been a Java developer for any length of time, you’ve heard the words “multithreading” and “concurrency.” They can sound intimidating, conjuring images of deadlocks, race conditions, and nights spent debugging bizarre, unpredictable behavior. But the truth is, in the modern world of multi-core processors, concurrency isn’t optional—it’s essential for building responsive, high-performance applications.

The good news? Java’s approach to concurrency has undergone a massive evolution, a journey from unwieldy, manual controls to elegant, high-level abstractions. It’s like going from manually shifting gears on a Model T to driving a modern car with a sophisticated automatic transmission.

Let’s take a walk through this evolution. Understanding this journey doesn’t just teach you history; it gives you a mental model for choosing the right tool for the job today.

Chapter 1: The Wild West — Thread and Runnable

In the beginning, there was Thread. This is the bedrock of Java concurrency. It’s a direct, one-to-one mapping to an operating system (OS) thread. You want something to run in the background? You create a Thread and you tell it what to do via a Runnable.

Continue reading From Raw Threads to Virtual Threads: A Developer’s Guide to Java Concurrency

The Visitor Pattern: A Practical Guide to Adding New Operations

As software engineers, we often face a dilemma: we have a stable set of classes, but we constantly need to add new functionality that operates on them. Do we keep modifying these existing, stable classes? That can be risky and violates the Open/Closed Principle. Or is there a cleaner way?

Enter the Visitor Design Pattern. It’s a behavioral pattern that lets you add new operations to a set of objects without changing the classes of those objects. It’s like hiring a specialist to work on your existing equipment, rather than trying to rebuild the equipment every time you need a new task done.

In this guide, we’ll break down the Visitor pattern, understand the problem it solves, and walk through a practical Java example.

The Core Problem: Scattered Logic

Imagine you’re building an e-commerce platform. You have a shopping cart that can hold different types of items. Let’s keep it simple and say you have Book and Electronics items.

Continue reading The Visitor Pattern: A Practical Guide to Adding New Operations

Solved: java.lang.NoClassDefFoundError: org/hibernate/cache/CacheProvider

Encountering a java.lang.NoClassDefFoundError can be one of the most frustrating issues when working with Java applications. This particular error — org/hibernate/cache/CacheProvider — is a common stumbling block for developers upgrading or mixing Hibernate versions. Let’s break down what it means and how to fix it.

Understanding the Error

The NoClassDefFoundError occurs when the JVM tries to load a class by its fully qualified name but cannot find its definition at runtime — even though the class existed at compile time. In this case, org.hibernate.cache.CacheProvider was the standard interface for Hibernate second-level cache integration in Hibernate 3.x. It was deprecated in Hibernate 4 and completely removed in Hibernate 5+, replaced by org.hibernate.cache.spi.RegionFactory.

Continue reading Solved: java.lang.NoClassDefFoundError: org/hibernate/cache/CacheProvider