Skip to main content

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: Insertion Order: The default behavior, where elements are iterated in the order they were first inserted into the map. 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 HashMap, LinkedHashMap 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.

8086 Assembly Program to Calculate the Factorial of an Integer Using Loops and Registers

In this post, we'll walk through an 8086 assembly program that calculates the factorial of a given integer. This program highlights the power of the 8086's loop instruction and the use of general-purpose registers for iterative calculations. We'll use the AX register as an accumulator for the result and the CX register as a loop counter, which is its special-purpose function. Let's get to the code!

Custom Validation in Spring Boot: Beyond the Basics!

A custom Bean Validation constraint built from scratch on Spring Boot 4.1.1 and Jakarta Validation 3.1: the javax→jakarta namespace fix Boot 3 already required, field- and class-level constraints on Java records, and what spring.mvc.problemdetails.enabled does and does not fix.

JUnit @BeforeAll and @AfterAll: One-Time Setup and Teardown

How JUnit @BeforeAll and @AfterAll work on JUnit 6 and 5: why they are static, how @TestInstance(PER_CLASS) lifts that, what happens when setup throws, and how @TempDir and the extension Store clean up shared resources for you. Every claim is backed by a run in a companion repository.

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:

Mastering Global Variables in JavaScript

Global variables in JavaScript are a topic that often sparks debate among developers. While they offer convenience, their misuse can lead to messy, hard-to-maintain code. At AnkurM.com, we believe in writing clean, robust JavaScript, and that includes understanding the right way to handle global variables. This guide will walk you through the various approaches, highlighting best practices and common pitfalls. Let’s dive in! Understanding the Global Scope In web browsers, the global scope is represented by the window object (or self or frames, though window is most common). Any variable declared outside of a function or block, or implicitly declared without let, const, or var, becomes a property of the global object.

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?

Configuring Tomcat to See the Real Client IP Behind a Proxy or Load Balancer

When you deploy a Java web application on Apache Tomcat and place it behind a reverse proxy or a load balancer (like Nginx, Apache httpd, or an AWS Elastic Load Balancer), a common challenge arises: Tomcat no longer sees the original client’s IP address. Instead, methods like request.getRemoteAddr() return the IP address of the load balancer itself. This can be a significant problem for features that rely on the client’s IP, such as: Security and rate-limiting Geolocation-based services Audit logging and analytics User session tracking Fortunately, Tomcat provides a clean, built-in solution to this problem: the RemoteIpValve. This post will guide you through understanding the problem and implementing the fix in your server.xml file.

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.

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.