DEV Community

Cover image for My Top 10 Java Utility Functions You’ll Want to Steal
Chant Khialian
Chant Khialian

Posted on

My Top 10 Java Utility Functions You’ll Want to Steal

🔧 My Top 10 Java Utility Functions You’ll Want to Steal


By Shant Khayalian — Balian’s IT


Unlocking Java’s hidden gems with Bob’s everyday adventures.


đź§° The Power of Utility Functions


In Java development, utility functions are like the Swiss Army knives of coding — they provide reusable solutions to common problems, enhancing code readability and maintainability. Typically housed in utility classes (often with names ending in Utils), these static methods help avoid code duplication and promote best practices.


👨‍💻 Your Everyday Java Developer


To make our exploration relatable, let’s follow Bob, a Java developer navigating daily coding challenges. Through his experiences, we’ll see how utility functions can simplify tasks and improve code efficiency.


đź’ˇ Top 10 Java Utility Functions

<article>
  <h3>1. <code>isNullOrBlank(String input)</code></h3>
  <p><strong>Purpose:</strong> Checks if a string is null or contains only whitespace.</p>
  <pre><code>public static boolean isNullOrBlank(String input) {
return input == null || input.trim().isEmpty();
Enter fullscreen mode Exit fullscreen mode

}

Bob’s Scenario: Bob is validating user input from a form. Using isNullOrBlank, he ensures that fields aren't left empty or filled with just spaces.


<article>
  <h3>2. <code>capitalize(String input)</code></h3>
  <p><strong>Purpose:</strong> Capitalizes the first character of the string.</p>
  <pre><code>public static String capitalize(String input) {
if (isNullOrBlank(input)) return input;
return input.substring(0, 1).toUpperCase() + input.substring(1);
Enter fullscreen mode Exit fullscreen mode

}

Bob’s Scenario: While displaying user names, Bob wants to ensure they start with a capital letter for consistency.


<article>
  <h3>3. <code>join(List&lt;String&gt; list, String delimiter)</code></h3>
  <p><strong>Purpose:</strong> Joins a list of strings into a single string with a specified delimiter.</p>
  <pre><code>public static String join(List&lt;String&gt; list, String delimiter) {
return String.join(delimiter, list);
Enter fullscreen mode Exit fullscreen mode

}

Bob’s Scenario: Bob needs to display a list of selected items as a comma-separated string.


<article>
  <h3>4. <code>reverse(String input)</code></h3>
  <p><strong>Purpose:</strong> Reverses the given string.</p>
  <pre><code>public static String reverse(String input) {
return new StringBuilder(input).reverse().toString();
Enter fullscreen mode Exit fullscreen mode

}

Bob’s Scenario: Implementing a feature to check for palindromes, Bob uses reverse to compare strings.


<article>
  <h3>5. <code>isPalindrome(String input)</code></h3>
  <p><strong>Purpose:</strong> Checks if a string reads the same backward as forward.</p>
  <pre><code>public static boolean isPalindrome(String input) {
if (input == null) return false;
String clean = input.replaceAll("\\s+", "").toLowerCase();
return clean.equals(reverse(clean));
Enter fullscreen mode Exit fullscreen mode

}

Bob’s Scenario: Bob adds a fun feature to detect palindromic phrases entered by users.


<article>
  <h3>6. <code>safeParseInt(String input)</code></h3>
  <p><strong>Purpose:</strong> Safely parses a string to an integer, returning 0 if parsing fails.</p>
  <pre><code>public static int safeParseInt(String input) {
try {
    return Integer.parseInt(input);
} catch (NumberFormatException e) {
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

}

Bob’s Scenario: Processing form inputs, Bob uses safeParseInt to handle optional numeric fields gracefully.


<article>
  <h3>7. <code>distinctByKey(Function&lt;T, ?&gt; keyExtractor)</code></h3>
  <p><strong>Purpose:</strong> Filters a stream to ensure distinct elements based on a key.</p>
  <pre><code>public static &lt;T&gt; Predicate&lt;T&gt; distinctByKey(Function&lt;? super T, ?&gt; keyExtractor) {
Set&lt;Object&gt; seen = ConcurrentHashMap.newKeySet();
return t -&gt; seen.add(keyExtractor.apply(t));
Enter fullscreen mode Exit fullscreen mode

}

Bob’s Scenario: Bob processes a list of users and wants to remove duplicates based on email addresses.


<article>
  <h3>8. <code>retry(Runnable task, int attempts)</code></h3>
  <p><strong>Purpose:</strong> Retries a task a specified number of times if it fails.</p>
  <pre><code>public static void retry(Runnable task, int attempts) {
for (int i = 0; i &lt; attempts; i++) {
    try {
        task.run();
        return;
    } catch (Exception e) {
        if (i == attempts - 1) throw e;
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Bob’s Scenario: Bob implements a network call that occasionally fails; using retry, he attempts the call multiple times before giving up.


<article>
  <h3>9. <code>timeExecution(Runnable task)</code></h3>
  <p><strong>Purpose:</strong> Measures and logs the execution time of a task.</p>
  <pre><code>public static void timeExecution(Runnable task) {
long start = System.currentTimeMillis();
task.run();
long end = System.currentTimeMillis();
System.out.println("Execution time: " + (end - start) + " ms");
Enter fullscreen mode Exit fullscreen mode

}

Bob’s Scenario: Optimizing performance, Bob uses timeExecution to identify slow-running methods.


<article>
  <h3>10. <code>memoize(Function&lt;T, R&gt; function)</code></h3>
  <p><strong>Purpose:</strong> Caches the results of expensive function calls.</p>
  <pre><code>public static &lt;T, R&gt; Function&lt;T, R&gt; memoize(Function&lt;T, R&gt; function) {
Map&lt;T, R&gt; cache = new ConcurrentHashMap&lt;&gt;();
return input -&gt; cache.computeIfAbsent(input, function);
Enter fullscreen mode Exit fullscreen mode

}

Bob’s Scenario: Bob optimizes a recursive computation by caching results to avoid redundant processing.



đź§  FAQ

<h3>What is a utility function in Java?</h3>
<p>A utility function in Java is a static method that performs a commonly used, reusable operation — often unrelated to any specific object state.</p>

<h3>What is the use of a utility class in Java?</h3>
<p>A utility class groups multiple utility functions together for:</p>
<ul>
  <li>Code reuse</li>
  <li>Clean and DRY code</li>
  <li>Easy testing and debugging</li>
  <li>Faster development</li>
</ul>

<h3>How to import a utility class in Java?</h3>
<pre><code>import com.example.utils.AppUtils;
Enter fullscreen mode Exit fullscreen mode

import static com.example.utils.StringUtils.capitalize;
String name = capitalize("bob");

<h3>How to make a Java utility class?</h3>
<pre><code>public final class StringUtils {
private StringUtils() {
    throw new UnsupportedOperationException("Utility class");
}

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

public static String capitalize(String input) {
    if (input == null || input.isEmpty()) return input;
    return input.substring(0, 1).toUpperCase() + input.substring(1);
}
Enter fullscreen mode Exit fullscreen mode

}

Find us

Balian’s Blogs Balian’s
linkedin Shant Khayalian
Facebook Balian’s
X-platform Balian’s
web Balian’s
Youtube Balian’s

#Java #UtilityFunctions #CodeReuse #JavaBestPractices #CleanCode #JavaDevelopment

Top comments (0)