🧾 Introduction
In Part 1, we explored 10 essential utility functions covering validation, string handling, retry logic, and date/time formatting.
In this Part 2, we’ll go deeper and cover 15 more practical and modern utility methods — covering collections, files, optional handling, system info, and more — using Java 17–21 syntax and conventions.
Let’s continue!
11. coalesce(String... values)
Returns the first non-null and non-blank string.
✅ Implementation:
public static String coalesce(String... values) {
return Arrays.stream(values)
.filter(s -> s != null && !s.isBlank())
.findFirst()
.orElse("");
}
🔄 Usage:
String name = coalesce(inputName, defaultName, "Unknown");
12. toListOrEmpty(List<T> list)
Returns the given list or an empty list if null.
✅ Implementation:
public static <T> List<T> toListOrEmpty(List<T> list) {
return list == null ? List.of() : list;
}
🔄 Usage:
List<Order> orders = toListOrEmpty(user.getOrders());
🔢 13. joinWithComma(List<String> items)
Joins a list of strings into a comma-separated string.
✅ Implementation:
public static String joinWithComma(List<String> items) {
return items == null ? "" : String.join(", ", items);
}
🔄 Usage:
String tagLine = joinWithComma(List.of("Java", "Spring", "Docker"));
14. wrapWithQuotes(String value)
Wraps a string with double quotes.
✅ Implementation:
public static String wrapWithQuotes(String value) {
return "\"" + value + "\"";
}
🔄 Usage:
System.out.println(wrapWithQuotes("Ramesh")); // Output: "Ramesh"
15. asOptional(T value)
Wraps a nullable value into an Optional
.
✅ Implementation:
public static <T> Optional<T> asOptional(T value) {
return Optional.ofNullable(value);
}
🔄 Usage:
Optional<String> maybeName = asOptional(user.getName());
16. isEven(int number)
Checks if a number is even.
✅ Implementation:
public static boolean isEven(int number) {
return number % 2 == 0;
}
🔄 Usage:
if (isEven(10)) System.out.println("Even number!");
17. readFileContent(Path path)
Reads the content of a file into a string.
✅ Implementation:
public static String readFileContent(Path path) throws IOException {
return Files.readString(path);
}
🔄 Usage:
String content = readFileContent(Path.of("config.txt"));
18. writeToFile(Path path, String content)
Writes content to a file, overwriting if exists.
✅ Implementation:
public static void writeToFile(Path path, String content) throws IOException {
Files.writeString(path, content, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
🔄 Usage:
writeToFile(Path.of("log.txt"), "System started at " + LocalDateTime.now());
19. isPalindrome(String input)
Checks if a string is a palindrome.
✅ Implementation:
public static boolean isPalindrome(String input) {
if (input == null) return false;
String clean = input.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
return new StringBuilder(clean).reverse().toString().equals(clean);
}
🔄 Usage:
boolean result = isPalindrome("RaceCar"); // true
20. roundToTwoDecimals(double value)
Rounds a double value to two decimal places.
✅ Implementation:
public static double roundToTwoDecimals(double value) {
return Math.round(value * 100.0) / 100.0;
}
🔄 Usage:
double price = roundToTwoDecimals(199.999); // 200.0
21. getFileExtension(String filename)
Extracts the file extension from a filename.
✅ Implementation:
public static String getFileExtension(String filename) {
return Optional.ofNullable(filename)
.filter(f -> f.contains("."))
.map(f -> f.substring(f.lastIndexOf('.') + 1))
.orElse("");
}
🔄 Usage:
String ext = getFileExtension("notes.txt"); // txt
22. isValidURL(String url)
Validates a URL string using regex.
✅ Implementation:
public static boolean isValidURL(String url) {
return Optional.ofNullable(url)
.map(u -> u.matches("^(http|https)://[\\w.-]+(?:\\.[\\w.-]+)+.*$"))
.orElse(false);
}
🔄 Usage:
if (!isValidURL(inputUrl)) {
System.out.println("Invalid URL!");
}
23. generateRandomAlphanumeric(int length)
Generates a random alphanumeric string of the given length.
✅ Implementation:
public static String generateRandomAlphanumeric(int length) {
final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new Random().ints(length, 0, chars.length())
.mapToObj(chars::charAt)
.map(Object::toString)
.collect(Collectors.joining());
}
🔄 Usage:
String otp = generateRandomAlphanumeric(6);
24. getEnv(String key, String defaultValue)
Fetches an environment variable or returns a default value.
✅ Implementation:
public static String getEnv(String key, String defaultValue) {
return Optional.ofNullable(System.getenv(key)).orElse(defaultValue);
}
🔄 Usage:
String dbHost = getEnv("DB_HOST", "localhost");
25. safeCast(Object obj, Class<T> targetType)
Safely casts an object using Java 21’s pattern matching.
✅ Implementation (Java 21):
public static <T> Optional<T> safeCast(Object obj, Class<T> type) {
return (obj != null && type.isInstance(obj)) ? Optional.of(type.cast(obj)) : Optional.empty();
}
🔄 Usage:
Optional<String> name = safeCast(input, String.class);
✅ Avoids ClassCastException
in flexible APIs.
✅ Final Summary
Here are the remaining 15 utility functions we covered in this part:
- coalesce
- toListOrEmpty
- joinWithComma
- wrapWithQuotes
- asOptional
- isEven
- readFileContent
- writeToFile
- isPalindrome
- roundToTwoDecimals
- getFileExtension
- isValidURL
- generateRandomAlphanumeric
- getEnv
- safeCast
Combined with Part 1, these 25 utility functions can become a reliable part of your shared Java library, making development faster, cleaner, and more modern.
Here is the complete code in a single Java class for your reference:
package com.example.utils;
import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
public class JavaUtilsPart2 {
public static String coalesce(String... values) {
return Arrays.stream(values)
.filter(s -> s != null && !s.isBlank())
.findFirst()
.orElse("");
}
public static <T> List<T> toListOrEmpty(List<T> list) {
return list == null ? List.of() : list;
}
public static String joinWithComma(List<String> items) {
return items == null ? "" : String.join(", ", items);
}
public static String wrapWithQuotes(String value) {
return """ + value + """;
}
public static <T> Optional<T> asOptional(T value) {
return Optional.ofNullable(value);
}
public static boolean isEven(int number) {
return number % 2 == 0;
}
public static String readFileContent(Path path) throws IOException {
return Files.readString(path);
}
public static void writeToFile(Path path, String content) throws IOException {
Files.writeString(path, content, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
public static boolean isPalindrome(String input) {
if (input == null) return false;
String clean = input.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
return new StringBuilder(clean).reverse().toString().equals(clean);
}
public static double roundToTwoDecimals(double value) {
return Math.round(value * 100.0) / 100.0;
}
public static String getFileExtension(String filename) {
return Optional.ofNullable(filename)
.filter(f -> f.contains("."))
.map(f -> f.substring(f.lastIndexOf('.') + 1))
.orElse("");
}
public static boolean isValidURL(String url) {
return Optional.ofNullable(url)
.map(u -> u.matches("^(http|https)://[\w.-]+(?:\.[\w.-]+)+.*$"))
.orElse(false);
}
public static String generateRandomAlphanumeric(int length) {
final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new Random().ints(length, 0, chars.length())
.mapToObj(chars::charAt)
.map(Object::toString)
.collect(Collectors.joining());
}
public static String getEnv(String key, String defaultValue) {
return Optional.ofNullable(System.getenv(key)).orElse(defaultValue);
}
public static <T> Optional<T> safeCast(Object obj, Class<T> type) {
return (obj != null && type.isInstance(obj)) ? Optional.of(type.cast(obj)) : Optional.empty();
}
}
Comments
Post a Comment
Leave Comment