Fundamentals 16 min read

Master Java Collections: Avoid Common Pitfalls in Real-World Development

This article provides a comprehensive overview of the Java Collections Framework, explains frequent mistakes such as modifying collections during iteration or using toMap with null values, and introduces practical utility libraries like Hutool, Apache Commons Collections, and Guava to help developers write safer and more efficient code.

Shepherd Advanced Notes
Shepherd Advanced Notes
Shepherd Advanced Notes
Master Java Collections: Avoid Common Pitfalls in Real-World Development

Java collections form the backbone of data handling in Java applications. The framework is organized around two core interfaces, Collection and Map, with primary sub‑interfaces List, Set and Queue. Common concrete classes include ArrayList, LinkedList, HashSet, TreeSet, HashMap and TreeMap. Generics provide type safety, while the iterator interface offers a uniform way to traverse elements.

Common Pitfalls

1. Modifying a collection inside a foreach or for‑each loop

Using list.forEach(v -> { if (v == 2) list.remove(v); }) throws ConcurrentModificationException. The safe approach is to use an explicit Iterator and call iterator.remove(). The same rule applies to Set and Map.

2. Collectors.toMap() with null values

When converting a list of User objects to a map, a null name causes a NullPointerException. Solutions include filtering out null values, providing a custom merge function, or wrapping values with Optional:

// filter null values
Map<Long, String> userNameMap = list.stream()
    .filter(user -> user.getName() != null)
    .collect(Collectors.toMap(User::getId, User::getName));

// custom merge function for duplicate keys
Map<String, Long> map = list.stream()
    .collect(Collectors.toMap(User::getName, User::getId, (v1, v2) -> v2));

3. Duplicate keys in toMap()

If two User objects share the same name, toMap() throws IllegalStateException. Supplying a merge function resolves the conflict.

4. Arrays.asList() returns a fixed‑size list

Attempting list.add(4) on a list created by Arrays.asList() results in UnsupportedOperationException. The returned list reflects changes to the original array and vice versa.

5. Casting subList() to ArrayList

subList()

returns a view of the original list, not an ArrayList. Casting causes ClassCastException. Modifying the sub‑list affects the parent list, which can lead to unexpected logic errors.

Useful Utility Libraries

Hutool

Hutool provides concise collection utilities such as CollUtil.union() for list union and MapUtil.join() for merging maps.

List<String> list1 = CollUtil.newArrayList("A", "B", "C");
List<String> list2 = CollUtil.newArrayList("B", "C", "D");
List<String> union = CollUtil.union(list1, list2);
System.out.println("Union: " + union);

Map<String, Object> map1 = MapUtil.newHashMap();
map1.put("name", "John");
map1.put("age", 25);
Map<String, Object> map2 = MapUtil.newHashMap();
map2.put("gender", "Male");
Map<String, Object> resultMap = MapUtil.join(map1, map2);
System.out.println("Joined Map: " + resultMap);

Apache Commons Collections

The library offers CollectionUtils for operations like union, intersection, and immutable collections.

List<String> mutableList = new ArrayList<>();
mutableList.add("A");
mutableList.add("B");
List<String> immutableList = UnmodifiableList.unmodifiableList(mutableList);
// immutableList.add("C"); // throws UnsupportedOperationException

Guava

Guava adds advanced collection types such as RangeSet, Multimap, BiMap, and immutable collections.

RangeSet<Integer> rangeSet = TreeRangeSet.create();
rangeSet.add(Range.closedOpen(1, 5));
rangeSet.add(Range.closedOpen(5, 10));
System.out.println("Contains 3: " + rangeSet.contains(3)); // true

Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("Fruits", "Apple");
multimap.put("Fruits", "Banana");
System.out.println("Fruits: " + multimap.get("Fruits"));

ImmutableList<String> immutableList = ImmutableList.of("A", "B", "C");
// immutableList.add("D"); // throws UnsupportedOperationException

Conclusion

The Java Collections Framework offers a rich set of data structures and utilities. Understanding its hierarchy, choosing the right implementation for performance, and avoiding common pitfalls—especially when using streams, iterators, and third‑party utilities—lead to more robust and maintainable code.

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.

JavaconcurrencyGuavaCollectionsHutoolStreamsApache Commons
Shepherd Advanced Notes
Written by

Shepherd Advanced Notes

Dedicated to sharing advanced Java technical insights, daily work snippets, and the power of persistent effort.

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.