14 Advanced Java Collection Tricks to Write Cleaner Code

This article presents fourteen practical Java collection techniques—ranging from creating immutable and empty collections to using computeIfAbsent, Map.merge, Collectors.groupingBy, and EnumMap/EnumSet—each illustrated with concise code snippets and explanations that improve readability, safety, and performance in Spring Boot applications.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
14 Advanced Java Collection Tricks to Write Cleaner Code

Environment: Spring Boot 3.5.0.

1. Introduction

The Java Collections Framework is fundamental for everyday coding, yet many advanced usages are overlooked, leading to redundant, inefficient, or unsafe code. This guide covers fourteen high‑level tricks that simplify code, boost performance, and increase robustness.

2.1 Create Empty Collections

Traditional way:

List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
Map<String, String> map = new HashMap<>();

Preferred way using shared immutable singletons:

List<String> list = Collections.emptyList();
Set<String> set = Collections.emptySet();
Map<String, String> map = Collections.emptyMap();

Memory‑efficient: reuses a singleton instance.

Immutable: prevents accidental modification.

Expressive: clearly conveys intent.

2.2 Create Immutable Collections (Java 9+)

Factory methods simplify small immutable collections:

List<String> fruits = List.of("Apple", "Banana", "Mango");
Set<Integer> ids = Set.of(1, 2, 3);
Map<Integer, String> map = Map.of(1, "A", 2, "B");

Concise and readable syntax.

Immutable by default, avoiding accidental changes.

More efficient than wrapping mutable collections with Collections.unmodifiable*.

2.3 Return Safe Immutable Collections from APIs

Do not expose mutable internal collections directly:

public List<String> getItems(List<String> items) {
    return Collections.unmodifiableList(items);
    // or
    // return List.copyOf(items);
}

Protects internal data from external modification.

Improves encapsulation.

Prevents bugs caused by unintended mutations.

2.4 One‑Line Collection Conversion

Instead of manual loops:

for (String s : list) {
    set.add(s);
}

Use constructors:

Set<String> set = new HashSet<>(list);
List<String> list2 = new ArrayList<>(set);

Code becomes shorter and clearer.

Reduces boilerplate and error‑prone loops.

2.5 Collection Sorting

Basic sorting: Collections.sort(list); Custom sorting with Lambda (Java 8+):

list.sort(Comparator.comparing(String::length));

Compact syntax.

Flexible custom ordering.

Eliminates redundant code.

2.6 Use computeIfAbsent to Replace Null‑Check

Traditional approach:

if (!map.containsKey(key)) {
    map.put(key, new ArrayList<>());
}
map.get(key).add(value);

Improved version:

map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);

More concise and readable.

Avoids duplicate map lookups.

Prevents NullPointerException.

2.7 Count Element Occurrences

Traditional loop:

int count = 0;
for (String s : list) {
    if (s.equals("apple")) count++;
}

Compact version:

int count = Collections.frequency(list, "apple");

2.8 Check Collections for No Intersection

One‑line check:

boolean noCommon = Collections.disjoint(list1, list2);

Returns true when collections share no elements.

Efficient and expressive.

2.9 Shuffle Collection Elements Randomly

Randomize order: Collections.shuffle(list); Useful in game development, simulations, random test case generation, and load balancing.

2.10 Simplify Frequency Statistics with Map.merge()

Traditional counting:

if (map.containsKey(word)) {
    map.put(word, map.get(word) + 1);
} else {
    map.put(word, 1);
}

Elegant version: map.merge(word, 1, Integer::sum); Extremely concise syntax.

No explicit condition checks.

Ideal for word‑frequency, log analysis, and metric aggregation.

2.11 One‑Line Grouping with Collectors.groupingBy

Traditional multi‑line grouping can be verbose. One‑liner:

Map<String, List<User>> map = users.stream()
    .collect(Collectors.groupingBy(User::getCity));

2.12 Get Value with Default

Traditional null check:

Integer count = map.get(key);
if (count == null) count = 0;

Advanced form:

int count = map.getOrDefault(key, 0);

2.13 Safe Conditional Removal

Traditional removal requires iterator handling and can cause ConcurrentModificationException.

Modern approach: list.removeIf(s -> s.isEmpty()); Safe, concise, and avoids concurrent‑modification errors.

2.14 EnumMap / EnumSet Performance Boost

When enum values are used as keys, EnumMap and EnumSet outperform regular collections:

Map<Status, String> map = new EnumMap<>(Status.class);

These specialized collections provide superior speed and memory efficiency.

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.

JavaLambdaSpring BootCollectionsJava 9EnumMapMap.merge
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

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.