Category Archives: Java

Java Stream API: How to Get the Last Element

Java Streams provide elegant ways to process collections, but retrieving the last element isn’t as straightforward as calling a getLast() method. Since streams are designed for sequential processing without inherent indexing, developers need specific techniques to fetch the final element efficiently. This guide explores practical approaches to solve this common programming challenge.

Whether you’re processing large datasets or building concise functional pipelines, understanding these methods will help you write cleaner, more maintainable code.

The Core Challenge

Unlike List or Deque collections, Java Streams don’t maintain bidirectional iteration or direct index access. Once elements pass through the pipeline, they’re consumed. This design makes operations like stream().last() impossible without workarounds. However, several clever techniques leverage stream reduction and size information to achieve the desired result.

Approach 1: Using reduce() Method

The reduce() operation processes each element while retaining only the last one seen. This approach works beautifully for both sequential and parallel streams.

import java.util.Optional;
import java.util.stream.Stream;

public class LastElementWithReduce {
    public static void main(String[] args) {
        Stream fruitStream = Stream.of("apple", "banana", "cherry", "date");
        
        Optional lastElement = fruitStream.reduce((first, second) -> second);
        
        lastElement.ifPresent(element -> 
            System.out.println("Last fruit: " + element)
        );
    }
}
Continue reading Java Stream API: How to Get the Last Element

Get Year, Month, Day from Date in Java

Extracting individual date components like year, month, and day is a common requirement in Java applications. Whether you’re working with legacy Date objects or modern date-time APIs, this guide will show you multiple approaches to accomplish this task efficiently.


1. Using Calendar Class (Legacy Approach)

Before Java 8, the Calendar class was the standard way to extract date fields from a Date object. While it’s still supported, this approach is considered outdated and less intuitive than modern alternatives.

import java.util.Calendar;
import java.util.Date;

public class DateExtractor {
    public static void main(String[] args) {
        Date currentDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // Months are 0-based
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        
        System.out.println("Year: " + year);
        System.out.println("Month: " + month);
        System.out.println("Day: " + day);
    }
}

Note: The Calendar.MONTH field returns values from 0 (January) to 11 (December), so you need to add 1 to get the standard 1-12 month numbering.

Continue reading Get Year, Month, Day from Date in Java

Building Native Images of Spring Boot Applications with GraalVM: A Step-by-Step Guide

In the ever-evolving landscape of cloud-native development and serverless architectures, the demand for applications with lightning-fast startup times and minimal memory footprints is greater than ever. Java, traditionally known for its “write once, run anywhere” philosophy, has sometimes faced criticism regarding these very aspects. However, with the advent of GraalVM and Spring Boot’s dedicated support, Java is now a formidable contender in this space.

This post will guide you through the process of building GraalVM native images of your Spring Boot native applications (specifically Spring Boot 3.x), demonstrating how to unlock significant optimizations in startup time and memory consumption, perfect for serverless Java and general cloud native Java deployments.

Why Native Images? The GraalVM Advantage

Traditional Java applications run on the Java Virtual Machine (JVM). While the JVM offers incredible runtime optimizations through its Just-In-Time (JIT) compiler, there’s an inherent overhead: the JVM itself needs to start, classes need to be loaded, and code needs to be JIT-compiled at runtime.

GraalVM Native Image technology compiles your Java application ahead-of-time (AOT) into a standalone executable. This executable includes the application code, required libraries, and a minimal runtime environment (the Substrate VM) – all compiled into a single binary.

The benefits are substantial:

  • Blazing Fast Startup: Native images typically start in milliseconds, making them ideal for serverless functions, microservices, and environments where rapid scaling is crucial.
  • Reduced Memory Footprint: By eliminating the JVM overhead and only including the necessary code paths, native images use significantly less memory.
  • Smaller Deployment Size: The resulting binary is often much smaller than a traditional JAR file bundled with a JRE.
  • Lower Resource Consumption: Less CPU and memory usage translates to lower operational costs in cloud environments.

Spring Boot 3.x has embraced GraalVM native image compilation with first-class support, making the process more seamless than ever.

Continue reading Building Native Images of Spring Boot Applications with GraalVM: A Step-by-Step Guide

Java 8: Exact Arithmetic Operations in the Math Class

With the arrival of Java 8, the java.lang.Math utility class received a bundle of new methods that let you work with floating‑point numbers at a higher level of precision. Whether you’re implementing numerical libraries, doing financial calculations, or simply trying to understand IEEE 754 behaviour in Java, these additions are invaluable. Below we’ll walk through the most useful operators, illustrate their usage, and explain why they matter.

1. Inspecting the Exponent

The Math.getExponent(double d) and Math.getExponent(float f) methods extract the unbiased exponent from a double or float. This is equivalent to stripping the mantissa and returning the raw exponent as an int.

double d = 8.0;              // 2³
int exp = Math.getExponent(d);
System.out.println(exp);      // prints 3

float f = 0.125f;            // 2⁻³
System.out.println(Math.getExponent(f)); // prints -3

These methods are often used for normalizing numbers or maps where the scale is critical.

Continue reading Java 8: Exact Arithmetic Operations in the Math Class

Securing Spring MVC with SiteMinder Pre‑Authentication – A Step‑by‑Step Guide

Enterprise Java applications often need to integrate with an existing Single Sign‑On (SSO) solution such as ‘IBM WebSphere SiteMinder’. SiteMinder handles the authentication at the web‑server or reverse‑proxy level and forwards the authenticated user data to the backend application through HTTP headers. When building a Spring 3 application (or a Spring MVC 5‑grade equivalent) you can take advantage of Spring Security’s pre‑authentication support to trust the SiteMinder credentials and establish a secure user context inside your app.

Below you’ll find a complete, hands‑on recipe that walks through:

  • Adding the required Spring Security libraries.
  • Configuring web.xml to inject the SiteMinder filter.
  • Defining the Spring Security context with a pre‑authenticated throbber.
  • Mapping SiteMinder headers to Spring Security principals and authorities.
  • Demonstrating a protected controller that relies on the information.

Feel free to copy, paste and tweak the code to fit your own application constraints.

Prerequisites

  1. Java 8+ and Maven (or Gradle).
  2. Spring MVC 3.x or any later single‑module Spine; the example works with Spring 3.0.
  3. Apache Tomcat (or any Servlet 3.0 compliant container) with SiteMinder installed.
  4. SiteMinder policy files properly configured to forward user and role attributes via HTTP headers.
Continue reading Securing Spring MVC with SiteMinder Pre‑Authentication – A Step‑by‑Step Guide

Why You Should Never Use == to Compare Floats and Doubles in Java

Picture this: you’ve written a piece of Java code that performs some calculations. The logic seems flawless. You have an if statement that checks if two double or float values are equal. But for some reason, the check keeps failing, even when you’re sure the numbers should be identical. What’s going on? Welcome to one of the most common pitfalls in programming: comparing floating-point numbers.

If you’ve ever written code like if (myDouble == 0.3), you might be in for a surprise. Let’s dive into why this is a bad idea and how to do it correctly.

The Hidden Problem with Floating-Point Numbers

The root of the issue lies in how computers store fractional numbers. Both float and double types in Java use a binary representation format (specifically, the IEEE 754 standard). The problem is that just like the fraction 1/3 cannot be perfectly represented as a finite decimal (it’s 0.33333…), many decimal fractions cannot be perfectly represented in binary.

For example, the number 0.1 in decimal is an infinitely repeating fraction in binary. Because the computer has to truncate this at some point, the value it stores is not exactly 0.1, but a very, very close approximation.

When you perform arithmetic with these approximations, the tiny precision errors can add up, leading to unexpected results.

Continue reading Why You Should Never Use == to Compare Floats and Doubles in Java

Demystifying Thread Safety in Java: A Practical Guide

Imagine you’re collaborating on a Google Doc. You write a sentence, and at the exact same moment, your colleague deletes the paragraph it’s in. The result? Chaos. A corrupted document, lost work, and confusion. This is precisely what can happen inside your Java application when multiple threads—independent paths of execution—try to access and modify the same data simultaneously. Welcome to the world of concurrency and the critical concept of thread safety.

An object or a piece of code is considered “thread-safe” if it continues to function correctly, without causing data corruption or unexpected behavior, even when accessed by multiple threads at the same time. Getting this right is the difference between a robust, predictable application and one that suffers from mysterious, hard-to-reproduce bugs.

The Villain of Our Story: The Race Condition

The most common concurrency problem is the race condition. It occurs when multiple threads “race” to access and change a shared resource, and the final outcome depends on the unpredictable order in which they execute.

Continue reading Demystifying Thread Safety in Java: A Practical Guide