Explain Codes LogoExplain Codes Logo

How do I convert a Java 8 IntStream to a List?

java
java-8
collections
performance
Alex KataevbyAlex Kataev·Aug 18, 2024
TLDR

To swiftly convert a Java 8 IntStream to a List<Integer>, use boxed() followed by collect(Collectors.toList()):

List<Integer> myList = IntStream.of(1, 2, 3).boxed().collect(Collectors.toList());

The boxed() method wraps primitive int values into Integer objects and collect(Collectors.toList()) converts these into the final List<Integer>.

Upgrade for Java 16 users

In Java 16, reduce your typed characters and acrobatics with the smoother toList method :

List<Integer> myList = IntStream.of(1, 2, 3).boxed().toList();

This nifty method provides an unmodifiable List, scaling up your performance game.

Eclipse Collections: The Ferrari of conversions

Consider high performance Eclipse Collections when you need to live life in the fast lane:

MutableIntList intList = IntStream.of(1, 2, 3).collect( MutableIntList::new, MutableIntList::add, MutableIntList::addAll);

Why? It shuns the annoying boxing overhead. Bye unnecessary baggage!

Manual driving: custom collectors

If you like to drive manual or just staying classy with functional programming, create a List<Integer> using custom collector functions:

List<Integer> myList = IntStream.of(1, 2, 3) .collect(ArrayList::new, ArrayList::add, (list1, list2) -> list1.addAll(list2));

Comment: Because some of us like it old school.

When immutability is a religion

To enforce immutability post Java 8 and pre Java 16:

List<Integer> immutableList = Collections.unmodifiableList( IntStream.of(1, 2, 3).boxed().collect(Collectors.toList()) );

This shields your List from meddlesome mods, throwing UnsupportedOperationException if any dares.

Before vs. After

Before: 🔢➡️🔢➡️🔢➡️🔢 // Marathon After : 🚌 [🔢, 🔢, 🔢, 🔢] // Relax, your transit is here!

Stream to List: Faster than your food delivery!

Dealing with int array refugees

If you have an int array begging for conversion, Arrays.stream is your hero:

int[] numbers = {1, 2, 3}; List<Integer> myList = Arrays.stream(numbers).boxed().collect(Collectors.toList());

Comment: Who said arrays can't be elegant?

For the data behemoths

Handling large datasets? Choose your collection based on usage. Index-based access? Definitely List. Else, consider Set/Map based on data uniqueness and access needs.

Watch your step: Potential pitfalls

That boxing glove can punch

The ergonomic boxing does levy a cost on performance. For large collections or high-use scenarios, think about the overhead.

Immortality has a price

Immutable lists sound cool until you try to modify them. Sudden UnsupportedOperationException can ruin your coffee break.