Boost Java Productivity: Essential Utility Libraries and Code Tricks
This article introduces a curated collection of Java utility libraries—including Apache Commons, Commons Collections, Commons BeanUtils, Commons IO, and Google Guava—along with concise code examples that demonstrate common tasks such as string joining, case‑insensitive comparison, collection operations, date formatting, and advanced data structures, helping developers write cleaner, more efficient code.
1. Java built‑in utility methods
1.1 Join a List into a comma‑separated string
List<String> list = Arrays.asList("a", "b", "c");
// Using streams
String join = list.stream().collect(Collectors.joining(","));
System.out.println(join); // a,b,c
// Using String.join
join = String.join(",", list);
System.out.println(join); // a,b,c1.2 Case‑insensitive string comparison
if (strA.equalsIgnoreCase(strB)) {
System.out.println("相等");
}1.3 Object equality with null‑safety
Use Objects.equals(a, b) to avoid NullPointerException. 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
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 null/blank 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 len = cs == null ? 0 : cs.length();
if (len == 0) return true;
for (int i = 0; i < len; 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 capitalized = StringUtils.capitalize(str);
System.out.println(capitalized); // Yideng2.1.3 Repeat a string
String repeated = StringUtils.repeat("ab", 2);
System.out.println(repeated); // abab2.1.4 Date formatting utilities
// 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 Temporary pair/triple objects
ImmutablePair<Integer, String> pair = ImmutablePair.of(1, "yideng");
System.out.println(pair.getLeft() + "," + pair.getRight()); // 1,yideng
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 null/empty checks
public static boolean isEmpty(final Collection<?> coll) {
return coll == null || coll.isEmpty();
}
public static boolean isNotEmpty(final Collection<?> coll) {
return !isEmpty(coll);
}2.2.2 Set operations
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 (bean manipulation)
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
// Bean ↔ Map conversion
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(list);
List<List<Integer>> partitions = Lists.partition(list, 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 (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> distinct = multiset.elementSet();
System.out.println(distinct); // [orange, apple]
multiset.setCount("apple", 5);These libraries and snippets provide ready‑made solutions for many everyday Java development tasks, dramatically reducing boilerplate code and improving readability.
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.
ITFLY8 Architecture Home
ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.
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.
