Common Java Utility Libraries and Their Usage
This article introduces essential Java utility libraries—including built‑in methods, Apache Commons, and Google Guava—explaining their key features and providing code examples that show how to simplify common tasks such as string handling, collection operations, object mapping, and file I/O.
After years of work, many developers discover that numerous utility libraries can greatly reduce code and improve development efficiency, yet junior developers often overlook them. This article introduces several essential Java utility libraries and demonstrates common usage patterns.
1. Java Built‑in Utility Methods
1.1 List concatenation to a comma‑separated string
// How to join a list into a comma‑separated string a,b,c
List<String> list = Arrays.asList("a", "b", "c");
// First method using streams
String join = list.stream().collect(Collectors.joining(","));
System.out.println(join); // a,b,c
// Second method using String.join
String join2 = String.join(",", list);
System.out.println(join2); // a,b,c1.2 Case‑insensitive string comparison
if (strA.equalsIgnoreCase(strB)) {
System.out.println("相等");
}1.3 Object equality comparison with null‑safety
When using equals to compare objects, a null check on the left operand is required to avoid NullPointerException. The Objects.equals method handles this safely.
Objects.equals(strA, strB);Source implementation:
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}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
Apache Commons is a powerful and widely used set of utility libraries. Below are some of the most common modules.
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 emptiness checks
Methods work with any CharSequence (e.g., String, StringBuilder, StringBuffer).
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); // Yideng2.1.3 Repeat a string
String str = StringUtils.repeat("ab", 2);
System.out.println(str); // abab2.1.4 Date formatting utilities
// Date → String
String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
System.out.println(date); // e.g., 2021-05-01 01:01:01
// String → Date
Date date2 = DateUtils.parseDate("2021-05-01 01:01:01", "yyyy-MM-dd HH:mm:ss");
// Add one hour
Date date3 = DateUtils.addHours(new Date(), 1);2.1.5 Pair and Triple for temporary objects
// Pair (two fields)
ImmutablePair<Integer, String> pair = ImmutablePair.of(1, "yideng");
System.out.println(pair.getLeft() + "," + pair.getRight()); // 1,yideng
// Triple (three fields)
ImmutableTriple<Integer, String, Date> triple = ImmutableTriple.of(1, "yideng", new Date());
System.out.println(triple.getLeft() + "," + triple.getMiddle() + "," + triple.getRight());2.2 commons‑collections (collection utilities)
Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>2.2.1 Collection emptiness checks
public static boolean isEmpty(final Collection<?> coll) {
return coll == null || coll.isEmpty();
}
public static boolean isNotEmpty(final Collection<?> coll) {
return !isEmpty(coll);
}Set operations:
// Intersection
Collection<String> intersect = CollectionUtils.retainAll(listA, listB);
// Union
Collection<String> union = CollectionUtils.union(listA, listB);
// Difference
Collection<String> diff = CollectionUtils.subtract(listA, listB);2.3 commons‑beanutils (bean manipulation)
Maven dependency:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>Example bean:
public class User {
private Integer id;
private String name;
}Set properties and convert between bean and map:
User user = new User();
BeanUtils.setProperty(user, "id", 1);
BeanUtils.setProperty(user, "name", "yideng");
System.out.println(BeanUtils.getProperty(user, "name")); // yideng
Map<String, String> map = BeanUtils.describe(user);
System.out.println(map); // {id=1, name=yideng}
User newUser = new User();
BeanUtils.populate(newUser, map);
System.out.println(newUser);2.4 commons‑io (IO utilities)
Maven dependency:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>File operations:
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> list2 = Lists.newArrayList(1, 2, 3);
List<Integer> reverse = Lists.reverse(list2);
System.out.println(reverse); // [3, 2, 1]
List<List<Integer>> partition = Lists.partition(list2, 10);
Map<String, String> map = Maps.newHashMap();
Set<String> set = Sets.newHashSet();3.2 Advanced collection utilities
3.2.1 Multimap (one key → multiple values)
Multimap<String, Integer> map = ArrayListMultimap.create();
map.put("key", 1);
map.put("key", 2);
Collection<Integer> values = map.get("key");
System.out.println(map); // {key=[1, 2]}
Map<String, Collection<Integer>> asMap = map.asMap();3.2.2 BiMap (bijective map)
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);
System.out.println(row); // {男=yideng, 女=Lily}
Map<Integer, String> column = table.column("男");
System.out.println(column); // {18=yideng}3.2.4 Multiset (bag for counting)
Multiset<String> multiset = HashMultiset.create();
multiset.add("apple");
multiset.add("apple");
multiset.add("orange");
System.out.println(multiset.count("apple")); // 2
Set<String> set = multiset.elementSet();
System.out.println(set); // [apple, orange]
Iterator<String> it = multiset.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
multiset.setCount("apple", 5);The article concludes by inviting readers to share additional useful utility methods or libraries they know.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
