🔧 Top 25 Utility Functions Every Java Project Needs - Part 1

 ðŸ§¾ Introduction

Whether you’re working on a small utility tool or a massive enterprise application, certain utility functions are always helpful. They save time, reduce repetition, and improve code quality.

In this two-part guide, we’ll cover 25 essential utility functions — written using modern Java features. In Part 1, we'll explore the first 10.

1. isNullOrBlank(String input)

Checks whether a string is null or blank (empty or whitespace only).

✅ Java Implementation:

public static boolean isNullOrBlank(String input) {
return input == null || input.isBlank();
}

🔄 Usage:

if (isNullOrBlank(user.getName())) {
throw new IllegalArgumentException("Name cannot be blank");
}

2. capitalize(String input)

Converts the first letter to uppercase and leaves the rest unchanged.

✅ Java Implementation:

public static String capitalize(String input) {
if (isNullOrBlank(input)) return input;
return input.substring(0, 1).toUpperCase() + input.substring(1);
}

🔄 Usage:

String title = capitalize("java"); // Output: Java

3. safeToString(Object obj)

Safely converts an object to a string, returning an empty string if null.

✅Java Implementation:

public static String safeToString(Object obj) {
return Optional.ofNullable(obj).map(Object::toString).orElse("");
}

🔄 Usage:

System.out.println("User: " + safeToString(user.getUsername()));

4. generateUUID()

Generates a universally unique identifier.

✅ Java Implementation:

public static String generateUUID() {
return UUID.randomUUID().toString();
}

🔄 Usage:

String transactionId = generateUUID();

5. isNumeric(String str)

Checks whether a string contains only digits.

✅ Java Implementation:

public static boolean isNumeric(String str) {
return Optional.ofNullable(str)
.map(s -> s.matches("\\d+"))
.orElse(false);
}

🔄 Usage:

if (isNumeric(ageInput)) {
int age = Integer.parseInt(ageInput);
}

6. removeDuplicates(List<T> list)

Removes duplicate entries from a list while preserving order.

✅ Java Implementation:

public static <T> List<T> removeDuplicates(List<T> list) {
return list == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(list));
}

🔄 Usage:

List<String> tags = removeDuplicates(List.of("java", "spring", "java"));

7. formatDate(LocalDateTime dt, String pattern)

Formats a date using the specified pattern.

✅ Java Implementation:

public static String formatDate(LocalDateTime dt, String pattern) {
return dt.format(DateTimeFormatter.ofPattern(pattern));
}

🔄 Usage:

String formatted = formatDate(LocalDateTime.now(), "dd-MM-yyyy HH:mm");

8. parseDate(String dateStr, String pattern)

Parses a string into a LocalDateTime object.

✅ Java Implementation:

public static LocalDateTime parseDate(String dateStr, String pattern) {
return LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
}

🔄 Usage:

LocalDateTime dt = parseDate("11-04-2025 10:30", "dd-MM-yyyy HH:mm");

9. isValidEmail(String email)

Checks whether the input is a valid email address.

✅Java Implementation:

public static boolean isValidEmail(String email) {
return Optional.ofNullable(email)
.map(e -> e.matches("^[\\w._%+-]+@[\\w.-]+\\.[a-zA-Z]{2,}$"))
.orElse(false);
}

🔄 Usage:

if (!isValidEmail(user.getEmail())) {
throw new IllegalArgumentException("Email is invalid.");
}

10. retry(Runnable task, int attempts)

Retries a failing task a fixed number of times.

✅ Java Implementation:

public static void retry(Runnable task, int attempts) {
Objects.requireNonNull(task);
for (int i = 0; i < attempts; i++) {
try {
task.run();
return;
} catch (Exception ex) {
if (i == attempts - 1) throw ex;
}
}
}

🔄 Usage:

retry(() -> sendEmail(), 3);

✅ Especially useful for network calls or flaky I/O operations.


✅ Final Thoughts for Part 1

These 10 utility functions can help you simplify common tasks such as formatting, validation, collection handling, and error retry logic.

They are:

  1. isNullOrBlank
  2. capitalize
  3. safeToString
  4. generateUUID
  5. isNumeric
  6. removeDuplicates
  7. formatDate
  8. parseDate
  9. isValidEmail
  10. retry

Here is the complete code in a single Java class for your reference:

package com.example.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class JavaUtilsPart1 {

public static boolean isNullOrBlank(String input) {
return input == null || input.isBlank();
}

public static String capitalize(String input) {
if (isNullOrBlank(input)) return input;
return input.substring(0, 1).toUpperCase() + input.substring(1);
}

public static String safeToString(Object obj) {
return Optional.ofNullable(obj).map(Object::toString).orElse("");
}

public static String generateUUID() {
return UUID.randomUUID().toString();
}

public static boolean isNumeric(String str) {
return Optional.ofNullable(str)
.map(s -> s.matches("\\d+"))
.orElse(false);
}

public static <T> List<T> removeDuplicates(List<T> list) {
return list == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(list));
}

public static String formatDate(LocalDateTime dt, String pattern) {
return dt.format(DateTimeFormatter.ofPattern(pattern));
}

public static LocalDateTime parseDate(String dateStr, String pattern) {
return LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
}

public static boolean isValidEmail(String email) {
return Optional.ofNullable(email)
.map(e -> e.matches("^[\\w._%+-]+@[\\w.-]+\\.[a-zA-Z]{2,}$"))
.orElse(false);
}

public static void retry(Runnable task, int attempts) {
Objects.requireNonNull(task);
for (int i = 0; i < attempts; i++) {
try {
task.run();
return;
} catch (Exception ex) {
if (i == attempts - 1) throw ex;
}
}
}
}

Each function is stateless, reusable, and designed for readability and testability.

📌 Next Up:
In Part 2, we’ll cover 15 more utility methods, including file utilities, advanced collection helpers, string transformation tools, optional-safe handling, and more.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare