Boost Java Productivity: Essential Utility Libraries and Code Tricks

This article introduces a collection of powerful Java utility libraries—including built‑in methods, Apache Commons, and Google Guava—showing practical code snippets for string handling, collection operations, object mapping, file I/O, and advanced data structures to dramatically reduce boilerplate and improve development efficiency.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Boost Java Productivity: Essential Utility Libraries and Code Tricks

1. Java Built‑in Utility Methods

1.1 Join List to a Comma‑Separated String

// How to join a List into a comma‑separated string
List<String> list = Arrays.asList("a", "b", "c");
String join = list.stream().collect(Collectors.joining(",")); // a,b,c
// Or using String.join
String join2 = String.join(",", list); // a,b,c

1.2 Compare Two Strings Ignoring Case

if (strA.equalsIgnoreCase(strB)) {
    System.out.println("相等");
}

1.3 Compare Two Objects Safely

Use Objects.equals to avoid NullPointerException when comparing objects.

Objects.equals(strA, strB);

1.4 Intersection of Two Lists

List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<String> list2 = new ArrayList<>();
list2.add("a");
list2.add("b");
list2.add("d");
list1.retainAll(list2);
System.out.println(list1); // [a, b]

2. Apache Commons Utility Libraries

2.1 commons‑lang3 (Enhanced java.lang)

Maven dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

2.1.1 String Empty Checks

public static boolean isEmpty(final CharSequence cs) {
    return cs == null || cs.length() == 0;
}
public static boolean isNotEmpty(final CharSequence cs) {
    return !isEmpty(cs);
}
public static boolean isBlank(final CharSequence cs) {
    int strLen = length(cs);
    if (strLen == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if (!Character.isWhitespace(cs.charAt(i))) {
            return false;
        }
    }
    return true;
}
public static boolean isNotBlank(final CharSequence cs) {
    return !isBlank(cs);
}

2.1.2 Capitalize First Letter

String str = "yideng";
String capitalize = StringUtils.capitalize(str);
System.out.println(capitalize); // Yideng

2.1.3 Repeat String

String str = StringUtils.repeat("ab", 2);
System.out.println(str); // abab

2.1.4 Date Formatting

// Date → String
String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
System.out.println(date);
// String → Date
Date parsed = DateUtils.parseDate("2021-05-01 01:01:01", "yyyy-MM-dd HH:mm:ss");
// Add one hour
Date plusOneHour = DateUtils.addHours(new Date(), 1);

2.1.5 Pair & Triple for Multiple Return Values

// Pair (two values)
ImmutablePair<Integer, String> pair = ImmutablePair.of(1, "yideng");
System.out.println(pair.getLeft() + "," + pair.getRight()); // 1,yideng
// Triple (three values)
ImmutableTriple<Integer, String, Date> triple = ImmutableTriple.of(1, "yideng", new Date());
System.out.println(triple.getLeft() + "," + triple.getMiddle() + "," + triple.getRight());

2.2 commons‑collections4 (Collection Utilities)

Maven dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

2.2.1 Collection Empty Checks

public static boolean isEmpty(final Collection<?> coll) {
    return coll == null || coll.isEmpty();
}
public static boolean isNotEmpty(final Collection<?> coll) {
    return !isEmpty(coll);
}
// Intersection, union, subtraction
Collection<String> intersect = CollectionUtils.retainAll(listA, listB);
Collection<String> union = CollectionUtils.union(listA, listB);
Collection<String> diff = CollectionUtils.subtract(listA, listB);

2.3 commons‑beanutils (Object‑Map Operations)

Maven dependency:

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>
public class User {
    private Integer id;
    private String name;
}
User user = new User();
BeanUtils.setProperty(user, "id", 1);
BeanUtils.setProperty(user, "name", "yideng");
System.out.println(BeanUtils.getProperty(user, "name")); // yideng
// Object ↔ Map
Map<String, String> map = BeanUtils.describe(user);
User newUser = new User();
BeanUtils.populate(newUser, map);

2.4 commons‑io (File I/O Utilities)

Maven dependency:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>
File file = new File("demo1.txt");
List<String> lines = FileUtils.readLines(file, Charset.defaultCharset());
FileUtils.writeLines(new File("demo2.txt"), lines);
FileUtils.copyFile(srcFile, destFile);

3. Google Guava Utility Library

Maven dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version>
</dependency>

3.1 Creating Collections

List<String> list = Lists.newArrayList();
List<Integer> numbers = Lists.newArrayList(1, 2, 3);
List<Integer> reversed = Lists.reverse(numbers); // [3,2,1]
List<List<Integer>> partitions = Lists.partition(numbers, 10);
Map<String, String> map = Maps.newHashMap();
Set<String> set = Sets.newHashSet();

3.2 Advanced Collection Types

3.2.1 Multimap (One key → Multiple values)

Multimap<String, Integer> multimap = ArrayListMultimap.create();
multimap.put("key", 1);
multimap.put("key", 2);
System.out.println(multimap); // {key=[1, 2]}
Map<String, Collection<Integer>> asMap = multimap.asMap();

3.2.2 BiMap (Bidirectional map, values must be unique)

BiMap<String, String> biMap = HashBiMap.create();
biMap.put("key", "value");
System.out.println(biMap); // {key=value}
BiMap<String, String> inverse = biMap.inverse();
System.out.println(inverse); // {value=key}

3.2.3 Table (Two‑dimensional map)

Table<Integer, String, String> table = HashBasedTable.create();
table.put(18, "男", "yideng");
table.put(18, "女", "Lily");
System.out.println(table.get(18, "男")); // yideng
Map<String, String> row = table.row(18); // {男=yideng, 女=Lily}
Map<Integer, String> column = table.column("男"); // {18=yideng}

3.2.4 Multiset (Set that counts occurrences)

Multiset<String> multiset = HashMultiset.create();
multiset.add("apple");
multiset.add("apple");
multiset.add("orange");
System.out.println(multiset.count("apple")); // 2
Set<String> distinct = multiset.elementSet(); // [apple, orange]
Iterator<String> it = multiset.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}
multiset.setCount("apple", 5);

These libraries and snippets can dramatically reduce boilerplate code, improve readability, and increase development speed for Java developers.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentCode ExamplesApache CommonsGoogle GuavaUtility Libraries
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.