π Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare
Even with all the improvements in modern Java (like records, sealed classes, and the new HTTP client), many everyday problems still come up in every Java project — validation, JSON parsing, mapping, formatting, and secure data handling.

Instead of rewriting the same code repeatedly, I keep these 15 reusable, production-ready snippets handy. They’re:
✔️ Java 17–21 compatible
✔️ Framework-agnostic (work with or without Spring)
✔️ Copy-paste-ready for your next project
We will discuss 15 reusable Java snippets:
- Centralized Validator
- Enum Parser
- Date Formatter
- HTTP Client
- JSON Mapper
- Result Wrapper
- Password Hasher
- Safe String Utils
- List-to-Map Converter
- Thread Sleep Utility
- List Cleaner
- File Reader
- Query Param Builder
- Retry Utility
- Zero-Padded Formatter
Let’s get into it.
1. Centralized Validator for Clean Service Code
Helps reduce repetitive null/blank checks in services or controllers.
public final class Validator {
public static void notBlank(String input, String field) {
if (input == null || input.isBlank()) {
throw new IllegalArgumentException(field + " must not be blank");
}
}
public static void notNull(Object obj, String field) {
if (obj == null) {
throw new IllegalArgumentException(field + " is required");
}
}
public static void lengthBetween(String str, int min, int max, String field) {
int len = str == null ? 0 : str.length();
if (len < min || len > max) {
throw new IllegalArgumentException(field + " must be between " + min + " and " + max + " characters");
}
}
}String.isBlank()(Java 17+) checks if a string is empty or contains only whitespace.- It’s an instance method, not static — cannot be called on
null. - Calling
isBlank()on anullstring throws aNullPointerException. - Always perform a null check before using
isBlank().
2. Enum-to-String and String-to-Enum Helper
Avoids fragile valueOf() calls and adds a graceful fallback for user input or database values.
public enum Status {
ACTIVE, INACTIVE;
public static Status from(String value) {
return Arrays.stream(values())
.filter(s -> s.name().equalsIgnoreCase(value))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Invalid status: " + value));
}
}Clean and null-safe enum parsing.
3. Modern Date Formatter (ISO + Display-Friendly)
Standard way to format dates for logs, APIs, or UI.
public final class DateFormatters {
public static final DateTimeFormatter ISO = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
public static final DateTimeFormatter DISPLAY = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm");
public static String nowIso() {
return OffsetDateTime.now().format(ISO);
}
public static String format(LocalDateTime time) {
return time.format(DISPLAY);
}
}✅ Use java.time APIs (fully thread-safe) — no need for SimpleDateFormat.
4. Lightweight HTTP Client (Java 11+)
No external library needed for basic GET/POST.
public final class HttpUtil {
private static final HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
public static String get(String url) throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
return client.send(request, HttpResponse.BodyHandlers.ofString()).body();
}
public static String post(String url, String jsonBody) throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
return client.send(request, HttpResponse.BodyHandlers.ofString()).body();
}
}Optional: Use sendAsync() for non-blocking requests.
5. Safe JSON Mapper with Jackson
Avoid repeated try/catch in every API layer.
public final class Json {
private static final ObjectMapper MAPPER = new ObjectMapper();
public static <T> T parse(String json, Class<T> type) {
try {
return MAPPER.readValue(json, type);
} catch (IOException e) {
throw new RuntimeException("Failed to parse JSON", e);
}
}
public static String toJson(Object obj) {
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to write JSON", e);
}
}
}✅ Ideal for Spring Boot or plain Java apps.
6. Result Wrapper for Clean Service Layers
Simplifies response models and success/error handling.
public record Result<T>(boolean success, T data, String message) {
public static <T> Result<T> ok(T data) {
return new Result<>(true, data, null);
}
public static <T> Result<T> fail(String msg) {
return new Result<>(false, null, msg);
}
}✅ Works well for internal service logic, controller responses, or APIs.
7. Password Hashing with BCrypt
Never store plain passwords. This snippet uses industry-standard encryption.
public final class PasswordUtil {
private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
public static String hash(String plainPassword) {
return encoder.encode(plainPassword);
}
public static boolean verify(String plain, String hashed) {
return encoder.matches(plain, hashed);
}
}Maven:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>6.1.2</version>
</dependency>✅ Avoid MD5 or SHA1. Use BCrypt for secure password storage.
8. Null-Safe String Comparison
Avoid NPEs in real-world comparisons.
public final class StringUtil {
public static boolean equalsIgnoreCase(String a, String b) {
return a != null && a.equalsIgnoreCase(b);
}
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
public static boolean isNullOrBlank(String s) {
return s == null || s.isBlank(); // Java 11+
}
}Use this across validators, mappers, or filters for robust string checks.
9. List to Map Converter (Avoid Boilerplate)
Quick way to group, map, or collect values.
public final class CollectionUtil {
public static <T, K> Map<K, T> toMap(List<T> list, Function<T, K> keyMapper) {
return list.stream().collect(Collectors.toMap(keyMapper, Function.identity(), (a, b) -> b));
}
public static <T, K, V> Map<K, V> toMap(List<T> list, Function<T, K> keyMapper, Function<T, V> valueMapper) {
return list.stream().collect(Collectors.toMap(keyMapper, valueMapper, (a, b) -> b));
}
}✅ Perfect for transforming list responses into key-value maps.
10. Safe Sleep Utility (Avoid Thread.sleep in Services)
Cleaner and reusable sleep with proper exception handling.
public final class ThreadUtil {
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore interrupt
throw new RuntimeException("Thread sleep interrupted", e);
}
}
}✅ Always restore interrupt status — don’t swallow it silently.
11. Clean List Filtering Utility
Filter out nulls, blanks, or empty strings from user input or configs.
public final class ListUtil {
public static List<String> cleanStrings(List<String> input) {
return input == null ? List.of() :
input.stream()
.filter(s -> s != null && !s.isBlank())
.toList();
}
}✅ Used in forms, config loading, or user input validation.
✅ Java 17+: toList() gives immutable list directly.
12. Read File Content into String
Read text files like configs, templates, logs, etc.
public final class FileUtil {
public static String read(String path) throws IOException {
return Files.readString(Path.of(path), StandardCharsets.UTF_8);
}
}✅ Java 11+
✅ Perfect for reading static assets or templates in microservices.
13. Convert Map to Query String
Useful for building URLs with parameters in REST clients.
public final class UrlUtil {
public static String toQueryParams(Map<String, String> params) {
return params.entrySet().stream()
.map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "=" +
URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
}
}✅ Combine with HttpUtil.get(url + "?" + queryString)
✅ Avoids manual string building for HTTP requests
14. Safe Retry Utility for External Calls
Retry external services, DB calls, or file operations.
public final class Retry {
public static <T> T withRetry(Supplier<T> task, int attempts, long delayMs) {
RuntimeException last = null;
for (int i = 0; i < attempts; i++) {
try {
return task.get();
} catch (RuntimeException e) {
last = e;
try {
Thread.sleep(delayMs);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
break;
}
}
}
throw last;
}
}✅ Great for non-critical external dependencies
✅ You can plug in any Supplier<T>: HTTP call, DB query, file read
15. Zero-Padded Number Formatter
Useful in invoice numbers, file names, codes like INV00045.
public final class FormatUtil {
public static String zeroPad(int number, int width) {
return String.format("%0" + width + "d", number);
}
}
// Example usage:
String padded = FormatUtil.zeroPad(45, 5); // Output: "00045"✅ Handy in billing systems, naming conventions, or reference numbers
✅ Summary
Here’s the final list of 15 truly reusable Java snippets:
- Centralized Validator
- Enum Parser
- Date Formatter
- HTTP Client
- JSON Mapper
- Result Wrapper
- Password Hasher
- Safe String Utils
- List-to-Map Converter
- Thread Sleep Utility
- List Cleaner
- File Reader
- Query Param Builder
- Retry Utility
- Zero-Padded Formatter
These are not just demos — they’re small, battle-tested code blocks that appear in nearly every real-world Java backend project.
Comments
Post a Comment
Leave Comment