Prev Next

Web / Apache Commons Collections Interview questions

1. What is Apache Commons Collections? 2. What are the main packages in Apache Commons Collections 4? 3. What is a Bag in Apache Commons Collections? 4. What are the types of Bag implementations in Commons Collections? 5. What is a BidiMap in Apache Commons Collections? 6. What is a MultiValuedMap in Apache Commons Collections? 7. What is the purpose of CollectionUtils in Apache Commons Collections? 8. What is the purpose of MapUtils in Apache Commons Collections? 9. What is the purpose of ListUtils in Apache Commons Collections? 10. What are Predicates in Apache Commons Collections? 11. What are Transformers in Apache Commons Collections? 12. What are Closures in Apache Commons Collections? 13. What is a Factory in Apache Commons Collections? 14. Define CircularFifoQueue in Apache Commons Collections? 15. What is an LRUMap in Apache Commons Collections? 16. What is a ReferenceMap in Apache Commons Collections? 17. What is a MultiKeyMap in Apache Commons Collections? 18. What is the purpose of IteratorUtils in Apache Commons Collections? 19. Describe the LoopingIterator class in Apache Commons Collections? 20. What is an OrderedMap in Apache Commons Collections? 21. What is a SortedBidiMap in Apache Commons Collections? 22. What is the purpose of ComparatorUtils in Apache Commons Collections? 23. Define FixedOrderComparator in Apache Commons Collections? 24. What is a PredicatedCollection in Apache Commons Collections? 25. What is a TransformedCollection in Apache Commons Collections? 26. What is the difference between a Map and a MultiValuedMap? 27. What is the difference between a BidiMap and a regular Map? 28. Why is CollectionUtils.isEmpty() preferred over calling isEmpty() directly? 29. How does a TreeBag maintain element ordering internally? 30. How does LRUMap decide which entry to evict? 31. What is the difference between HashBag and TreeBag? 32. Why do we use predicate chaining with allPredicate and anyPredicate? 33. How is UnmodifiableMap in Commons Collections different from java.util's Collections.unmodifiableMap? 34. What happens when you add a duplicate value to a BidiMap? 35. How does PredicatedList enforce validation on add operations? 36. Explain the internal working of CircularFifoQueue? 37. How can you optimize repeated multi-field lookups using MultiKeyMap? 38. What is the difference between Apache Commons Collections 3.x and 4.x? 39. Why should you use TransformedMap instead of manual validation in setters? 40. When should you choose Apache Commons Collections over Guava collections? 41. Explain the execution flow of CollectionUtils.collect()? 42. How is FactoryUtils used to lazily create objects? 43. Why is Apache Commons Collections associated with a well-known deserialization vulnerability? 44. What is the difference between the legacy MultiMap (3.x) and MultiValuedMap (4.x)? 45. How does ReferenceMap help prevent memory leaks in long-running caches? 46. Why doesn't a Bag simply behave like a Set? 47. How do you troubleshoot a ConcurrentModificationException when using CollectionUtils.filter()? 48. Explain the lifecycle of a ClosureUtils.chainedClosure() execution? 49. What is the difference between SetUtils.union() and manually merging two sets? 50. How does Commons Collections' Trie support prefix-based lookups?

1. What is Apache Commons Collections?

Apache Commons Collections is an open-source Java library that extends the standard Java Collections Framework (JCF) with extra data structures and utility classes that the JDK doesn't ship with out of the box. It adds interfaces like Bag , BidiMap , and MultiValuedMap , along with functional-sty...

Read full answer

2. What are the main packages in Apache Commons Collections 4?

Commons Collections 4 organizes its classes under org.apache.commons.collections4 and a set of focused sub-packages rather than one large flat package. bag - Bag implementations like HashBag and TreeBag bidimap - DualHashBidiMap, DualTreeBidiMap, TreeBidiMap map - LRUMap, ReferenceMap, MultiKeyMa...

Read full answer

3. What is a Bag in Apache Commons Collections?

A Bag is a collection interface that keeps count of how many times each distinct object appears, instead of just storing whether it's present or absent like a Set does. Calling add() twice with the same value doesn't get rejected the way a Set would reject it; instead the Bag simply increments...

Read full answer

4. What are the types of Bag implementations in Commons Collections?

Commons Collections ships two core, non-decorator Bag implementations, plus several decorators that layer behavior on top of either one. HashBag TreeBag backed by a HashMap; no ordering guarantee backed by a TreeMap; iterates in sorted order elements need only equals()/hashCode() elements must be...

Read full answer

5. What is a BidiMap in Apache Commons Collections?

A BidiMap is a Map that supports efficient lookup in both directions - by key, like a normal Map, and by value, using getKey(value) . To make reverse lookups unambiguous, a BidiMap enforces that values are also unique: putting a value that already exists under a different key removes that ol...

Read full answer

6. What is a MultiValuedMap in Apache Commons Collections?

A MultiValuedMap lets a single key be associated with more than one value, storing the values for each key in a backing Collection instead of a single slot. MultiValuedMap map = new ArrayListValuedHashMap<>(); map.put("fruits", "apple"); map.put("fruits", "banana"); Collectio...

Read full answer

7. What is the purpose of CollectionUtils in Apache Commons Collections?

CollectionUtils is a static helper class packed with null-safe operations for working with any java.util.Collection , so callers don't have to hand-roll the same boilerplate checks repeatedly. isEmpty(coll) / isNotEmpty(coll) - null-safe emptiness checks union() , intersection() , subtract() , di...

Read full answer

8. What is the purpose of MapUtils in Apache Commons Collections?

MapUtils provides static helpers for working with Map instances, focused on null-safety and type-safe value extraction. Methods like getString(map, key, defaultValue) , getInteger() , and getBoolean() pull a value out, cast it to the expected type, and fall back to a supplied default if the key i...

Read full answer

9. What is the purpose of ListUtils in Apache Commons Collections?

ListUtils focuses specifically on List-oriented operations that the JDK's Collections class doesn't cover directly. union() , intersection() , subtract() - combine two Lists while preserving duplicate counts, unlike Set-based operations isEqualList() - compares two Lists element-by-element, toler...

Read full answer

10. What are Predicates in Apache Commons Collections?

A Predicate is a functional interface with a single method, evaluate(T object) , that returns true or false - essentially a reusable, named condition. Predicate isLong = s -> s.length() > 5; List names = Arrays.asList("Al", "Alexandra", "Bo", "Bartholomew"); Collection ...

Read full answer

11. What are Transformers in Apache Commons Collections?

A Transformer defines one method, transform(I input) , that converts an input object into an output object of possibly a different type. Transformer toLength = String::length; List words = Arrays.asList("cat", "elephant", "dog"); Collection lengths = Collect...

Read full answer

12. What are Closures in Apache Commons Collections?

A Closure defines one method, execute(T input) , that performs a side effect on the input and returns nothing - the counterpart to Predicate (returns boolean) and Transformer (returns a new object). Closure printer = System.out::println; List names = Arrays.asList("Ann", "Ben")...

Read full answer

13. What is a Factory in Apache Commons Collections?

A Factory defines one no-argument method, create() , that produces a new instance of type T on demand - useful for deferring object creation until it's actually needed. Factory> listFactory = ArrayList::new; Map> lazyMap = MapUtils.lazyMap(new HashMap<>()...

Read full answer

14. Define CircularFifoQueue in Apache Commons Collections?

CircularFifoQueue is a fixed-capacity Queue implementation backed by an array that behaves like a circular buffer: once it's full, adding a new element automatically discards the oldest one instead of throwing an exception. CircularFifoQueue buffer = new CircularFifoQueue<>(3); buffer...

Read full answer

15. What is an LRUMap in Apache Commons Collections?

LRUMap is a bounded Map that automatically evicts its Least Recently Used entry once a configured maximum size is reached and a new entry needs to be inserted. LRUMap cache = new LRUMap<>(2); cache.put("a", "1"); cache.put("b", "2"); cache.get("a"); // "a" is now most recentl...

Read full answer

16. What is a ReferenceMap in Apache Commons Collections?

ReferenceMap is a Map whose keys and/or values are held through java.lang.ref soft or weak references rather than ordinary strong references. ReferenceMap cache = new ReferenceMap<>(ReferenceStrength.HARD, ReferenceStrength.SOFT); cache.put("payload", largeByteArray); // entr...

Read full answer

17. What is a MultiKeyMap in Apache Commons Collections?

MultiKeyMap lets you look values up using a combination of two to five key components instead of a single key object, without manually nesting Maps. MultiKeyMap distances = new MultiKeyMap<>(); distances.put("NYC", "LA", 2451.0); double d = distances.get("NYC", "LA"); // 2451...

Read full answer

18. What is the purpose of IteratorUtils in Apache Commons Collections?

IteratorUtils is a static helper class for constructing and combining Iterator instances beyond what the JDK provides directly. chainedIterator() - walks through several iterators back to back as one filteredIterator() - skips elements that fail a Predicate transformedIterator() - applies a Trans...

Read full answer

19. Describe the LoopingIterator class in Apache Commons Collections?

LoopingIterator wraps an existing Collection and iterates over it endlessly, restarting from the first element again once it reaches the end. List < String > players = Arrays.asList( "A" , "B" , "C" ); LoopingIterator < String > turnOrder = new LoopingIterator <> (players); for ( int i = 0 ; i...

Read full answer

20. What is an OrderedMap in Apache Commons Collections?

An OrderedMap extends the plain Map interface with the guarantee that entries can be walked in a defined, stable order, plus navigation methods like firstKey() , lastKey() , nextKey(K) , and previousKey(K) . OrderedMap < String, Integer > scores = new LinkedMap <> (); scores.put( "Ann" , 90 ...

Read full answer

21. What is a SortedBidiMap in Apache Commons Collections?

A SortedBidiMap combines the guarantees of a BidiMap (bidirectional key/value lookup with unique values) with those of a SortedMap (keys iterated in a defined sort order). SortedBidiMap < String, Integer > ranks = new DualTreeBidiMap <> (); ranks.put( "silver" , 2 ); ranks.put( "gold" , 1 );...

Read full answer

22. What is the purpose of ComparatorUtils in Apache Commons Collections?

ComparatorUtils supplies static helpers for building and combining Comparator instances without writing a new class for each variation. Comparator byLength = ComparatorUtils.naturalComparator(); Comparator reversed = ComparatorUtils.reversedComparator(byLength); String min = Compa...

Read full answer

23. Define FixedOrderComparator in Apache Commons Collections?

FixedOrderComparator sorts elements according to a custom sequence you supply up front, rather than their natural ordering or a computed rule. FixedOrderComparator statusOrder = new FixedOrderComparator<>("NEW", "IN_PROGRESS", "DONE"); List tickets = new ArrayList<>(List.of("DO...

Read full answer

24. What is a PredicatedCollection in Apache Commons Collections?

A PredicatedCollection is a decorator that wraps an existing Collection and validates every element against a supplied Predicate before allowing it to be added. Predicate nonEmpty = s -> s != null && !s.isEmpty(); Collection validated = PredicatedCollection.predicatedCollection(ne...

Read full answer

25. What is a TransformedCollection in Apache Commons Collections?

A TransformedCollection is a decorator that automatically runs a Transformer on every element as it's added, storing the transformed result instead of the original object. Transformer < String, String > upper = String::toUpperCase; Collection < String > normalized = TransformedCollection.transfor...

Read full answer

26. What is the difference between a Map and a MultiValuedMap?

A standard Map associates exactly one value with each key - calling put() a second time on the same key overwrites the first value. A MultiValuedMap associates each key with a Collection of values, so repeated put() calls accumulate rather than overwrite. Map MultiValuedMap ge...

Read full answer

27. What is the difference between a BidiMap and a regular Map?

A regular Map only supports efficient forward lookup, from key to value; finding a key from a given value means manually iterating every entry, an O(n) operation, and duplicate values are perfectly allowed. Map BidiMap reverse lookup requires manual iteration getKey(value) gives O(...

Read full answer

28. Why is CollectionUtils.isEmpty() preferred over calling isEmpty() directly?

Calling collection.isEmpty() directly assumes the reference itself is non-null; if collection is null - which happens often with optional fields, method parameters, or values pulled from external data sources - that call throws a NullPointerException before the emptiness check even runs. // fragi...

Read full answer

29. How does a TreeBag maintain element ordering internally?

TreeBag is backed internally by a TreeMap , mapping each distinct element to a mutable occurrence counter rather than storing the same element multiple times as separate map entries. TreeBag bag = new TreeBag<>(); bag.add("banana"); bag.add("apple"); bag.add("apple"); for (String fruit...

Read full answer

30. How does LRUMap decide which entry to evict?

LRUMap tracks access recency internally using a doubly linked structure layered over its hash table, similar to how LinkedHashMap behaves in access-order mode - every get() or put() moves the touched entry to the "most recently used" end of that internal ordering. graph LR A[put/get called] --> B...

Read full answer

31. What is the difference between HashBag and TreeBag?

Both are core Bag implementations, but they trade off ordering guarantees against raw performance in opposite directions. HashBag TreeBag backed by a HashMap backed by a TreeMap no defined iteration order iterates in sorted order O(1) average add/remove/getCount O(log n) add/remove/getCount eleme...

Read full answer

32. Why do we use predicate chaining with allPredicate and anyPredicate?

Predicate chaining lets you compose several independent validation rules into a single reusable Predicate object, instead of hard-coding a chain of if / else checks wherever the filtering logic is needed. Predicate nonEmpty = s -> s != null && !s.isEmpty(); Predicate isShort = s -...

Read full answer

33. How is UnmodifiableMap in Commons Collections different from java.util's Collections.unmodifiableMap?

Functionally, both wrap an existing Map and throw UnsupportedOperationException on any mutating call - put() , remove() , clear() - while still being a live read-through view: changes made to the original backing map are visible through the wrapper. Collections.unmodifiableMap() Commons Collectio...

Read full answer

34. What happens when you add a duplicate value to a BidiMap?

A BidiMap enforces that every value maps back to exactly one key, so inserting a value that's already associated with a different key doesn't create a second mapping - it silently removes the old mapping first. BidiMap < String, Integer > scores = new DualHashBidiMap <> (); scores.put( "alice" , ...

Read full answer

35. How does PredicatedList enforce validation on add operations?

PredicatedList decorates an existing List and intercepts every operation that would introduce a new element - add() , addAll() , set() , and even listIterator().add() / set() - running a supplied Predicate against the candidate element first. Predicate positive = n -> n != null && n >...

Read full answer

36. Explain the internal working of CircularFifoQueue?

CircularFifoQueue is backed by a fixed-size array rather than a linked structure, and it tracks the logical start and end of the queue using index counters that wrap around using modulo arithmetic once they reach the end of the array - hence "circular." graph TD A[add called] --> B{Queue at ma...

Read full answer

37. How can you optimize repeated multi-field lookups using MultiKeyMap?

A common but inefficient pattern for combining two lookup keys is nesting maps: Map> . Every lookup then costs two hash operations, plus a null-check on the intermediate map before you can even attempt the second lookup - and inserting a brand-new K1 means remembering to create the...

Read full answer

38. What is the difference between Apache Commons Collections 3.x and 4.x?

Commons Collections 4 was a deliberate, breaking redesign of the 3.x line rather than an incremental update, mainly to fix generics-related design problems that couldn't be solved without changing method signatures. Commons Collections 3.x Commons Collections 4.x org.apache.commons.collections or...

Read full answer

39. Why should you use TransformedMap instead of manual validation in setters?

Manual validation scattered across setters relies on every developer remembering to call the check before every insertion - a pattern that tends to erode as a codebase grows, since a new insertion path added later can easily forget to include the same validation the original ones had. Transformer...

Read full answer

40. When should you choose Apache Commons Collections over Guava collections?

Both libraries extend the JDK's collection APIs, but they emphasize different things, so the right choice depends on what a project already has and what specific structure it actually needs. Existing dependency - if a codebase already pulls in Commons Collections (common in older Spring or enterp...

Read full answer

41. Explain the execution flow of CollectionUtils.collect()?

CollectionUtils.collect(inputCollection, transformer) performs a functional "map" operation: it walks the input collection element by element, in iteration order, applying the given Transformer to each one, and appends every result to an output collection. graph TD A[Start: iterate input collecti...

Read full answer

42. How is FactoryUtils used to lazily create objects?

FactoryUtils wraps different object-creation strategies behind the single-method Factory interface, so creation logic can be deferred and swapped without touching the code that eventually calls create() . Factory> listFactory = FactoryUtils.instantiateFactory(ArrayList.class); Map...

Read full answer

43. Why is Apache Commons Collections associated with a well-known deserialization vulnerability?

In 2015, security researchers demonstrated that several of the library's reflective functor classes could be chained together to build a so-called "gadget chain" - a sequence of ordinary, individually harmless objects that, when deserialized in a specific combination, ends up executing arbitrary ...

Read full answer

44. What is the difference between the legacy MultiMap (3.x) and MultiValuedMap (4.x)?

In Commons Collections 3.x, MultiMap was defined by extending java.util.Map , where get(key) returned a raw Object that callers had to manually cast to a Collection - a design that predates generics being taken seriously and breaks the Map contract's expectation that get() returns a si...

Read full answer

45. How does ReferenceMap help prevent memory leaks in long-running caches?

A plain HashMap used as a cache holds a strong reference to every key and value it stores, which means nothing can ever be garbage collected until it's explicitly removed - if entries accumulate faster than they're evicted, the cache grows without bound and can eventually trigger an OutOfMemoryEr...

Read full answer

46. Why doesn't a Bag simply behave like a Set?

A Set 's contract is built entirely around uniqueness: calling add() with a value that's already present is a no-op that returns false , and the set's size only ever reflects distinct elements. That contract structurally cannot represent "how many times did this occur" - the information is thrown...

Read full answer

47. How do you troubleshoot a ConcurrentModificationException when using CollectionUtils.filter()?

CollectionUtils.filter(collection, predicate) mutates the collection in place : it walks the collection's own Iterator and calls Iterator.remove() on every element that fails the predicate. A ConcurrentModificationException (CME) shows up when something else disturbs that same collection while fi...

Read full answer

48. Explain the lifecycle of a ClosureUtils.chainedClosure() execution?

ClosureUtils.chainedClosure(closure1, closure2, ...) returns a single composite Closure that, when its execute(input) is called once, runs each wrapped closure in the order they were supplied, passing the same input object to every one of them in turn. graph TD A[chainedClosure.execute(input) cal...

Read full answer

49. What is the difference between SetUtils.union() and manually merging two sets?

SetUtils.union(setA, setB) returns a live, unmodifiable Set view that computes membership by delegating to the two original sets rather than eagerly copying every element into a new backing structure the moment it's called. Set teamA = Set.of("alice", "bob"); Set teamB = Set.of("b...

Read full answer

50. How does Commons Collections' Trie support prefix-based lookups?

The Trie interface, implemented by PatriciaTrie , organizes entries so that keys sharing a common prefix share the same internal path through the structure, rather than being scattered across independent hash buckets the way a HashMap would store them. Trie contacts = new Pat...

Read full answer

«
»

Comments & Discussions