Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

IntStream.boxed()

Turns a stream of int primitives into a stream of Integer objects.

Available since: Java 8

Syntax

Stream<Integer> boxed()

Return value

Stream<Integer>A stream of Integer with the same values.

Examples

A list of numbers from a range:

void main() {
    List<Integer> list = IntStream.rangeClosed(1, 5).boxed().toList();
    IO.println(list);
}

Output:

[1, 2, 3, 4, 5]

An int[] array into a sorted set without duplicates:

void main() {
    int[] scores = {5, 3, 5, 1};
    Set<Integer> unique = Arrays.stream(scores)
        .boxed()
        .collect(Collectors.toCollection(TreeSet::new));
    IO.println(unique);
}

Output:

[1, 3, 5]

Notes

IntStream has no toList() or collect(Collectors...): collections hold only objects, so boxed() comes first. LongStream and DoubleStream have the same method. The reverse step is mapToInt(Integer::intValue). If the values also need converting, write mapToObj(...) instead of boxed().map(...).

See also

In the tutorial

  • flatMap and numeric streams — flatMap and mapMulti for unfolding nested data, IntStream, LongStream and DoubleStream, switching between streams with boxed and mapToObj, summaryStatistics.

Thanks for reading!

Donate to the site — we work hard for you.