Explain Codes LogoExplain Codes Logo

Easy way to convert Iterable to Collection

java
collections
utility-methods
performance
Anton ShumikhinbyAnton Shumikhin·Aug 8, 2024
TLDR
// Paying homage to the mighty duck, turn your iterable ducklings into a collection of ducks, in one fell swoop Collection<String> collection = StreamSupport.stream(iterable.spliterator(), false) .collect(Collectors.toCollection(ArrayList::new));

This one-liner elegantly transforms an Iterable into an ArrayList. It uses Java's Stream API, specifically StreamSupport.stream to generate a stream from the Iterable, and Collectors.toCollection to herd these elements into an ArrayList.

Code Recipes: Top staring ingredients

Beyond the ArrayList, you often need different recipes for diverse Collection types. Here are some performance-focused culinary tips for you.

Custom Utility Methods: Chef’s secret weapon

Sometimes, your kitchen needs a special utility method. Here's a makeCollection function perfect for odd jobs around the kitchen: turning Iterable ingredients into a tasty Collection platter.

public static <E> Collection<E> makeCollection(Iterable<E> iter) { // Ducks march one by one, hoorah! hoorah! Collection<E> collection = new ArrayList<>(); iter.forEach(collection::add); return collection; }

Third Party Libraries: Mise en place

Guava and Apache Commons Collections are like having a sous-chef in the kitchen. They've done half the prep work for you!

  • List: Lists.newArrayList(iterable)
  • Set: Sets.newHashSet(iterable)

Remember, too many cooks can spoil the broth, and too many copies can bloat your memory. These operations make a fresh copy and may hog up memory.

Modern Java Ingredients: Sous-vide precision

If you're cooking up a storm with the latest Java versions, Stream.toList() prepares a perfect List from an Iterable.

List<String> list = StreamSupport.stream(iterable.spliterator(), false) .toList();

Pretty neat, huh? But handle with care: this returns an immutable list. No substitutions allowed in this recipe!

Essential Cooking Techniques: Get your hands dirty

To serve a perfect dish, choose the right technique. The same is true for our collections:

  • ArrayList: Like knife skills, it allows quick slicing and dicing (access).
  • LinkedList: Like slow cooking, it’s great for simmering (deletion/insertion) slowly.
  • HashSet: Like a colander, it’s perfect for draining duplicates.
  • TreeSet: Like a soufflé, it ensures your elements are puffed and sorted.

Mis en place: Check your ingredients

Working with Iterable involves meticulous ingredient checks:

  • Beware of the bad apple (null element) ruining your dish (causing NullPointerException).
  • Watch that temperamental soufflé (mutability). Collections returned from stream().collect() are ready for more action (modifiable).
  • If too many cooks (threads) are in the kitchen, watch out for clashing pans (concurrency).

Advanced techniques: Flambé with style

For a flamboyant finish, for each dish rather than collecting elements. The forEachRemaining method from Iterator is your secret flamethrower.

A perfect chef knows when to step back. Sometimes, the Iterable ingredients themselves are fresh and crisp (memory efficient) enough without the fancy footwork.