Web / Apache Commons Collections Interview questions
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.
Transformer<String, Integer> toLength = String::length; List<String> words = Arrays.asList("cat", "elephant"); Collection<Integer> lengths = CollectionUtils.collect(words, toLength); // or collect into a caller-supplied target: List<Integer> target = new ArrayList<>(); CollectionUtils.collect(words, toLength, target);
If no target collection is supplied, an ArrayList is created automatically to hold the results; if one is supplied, results are appended directly into it instead, which is useful when you want to accumulate transformed values into an already-existing collection rather than allocate a fresh one.
Conceptually it's the same idea as Java 8's Stream.map() followed by .collect(Collectors.toList()), but it predates streams, runs eagerly rather than lazily, and returns a fully materialized Collection immediately rather than a lazily-evaluated stream pipeline.
More Related questions...