Skip to lesson

IntStream, LongStream and DoubleStream

Adding up 100,000 order amounts through a normal stream wraps every number in an object. That is extra memory and work for plain numbers.

Why number streams exist: no boxing

A primitive stream (IntStream, LongStream, DoubleStream) holds numbers without boxing them into objects and offers number methods like sum and average.

A List<Integer> cannot hold a plain int. Each number is wrapped in an Integer object first. This wrapping is called boxing, and taking the int back out is called unboxing. So marks.stream() gives a Stream<Integer>, a stream of objects.

Left: a Stream<Integer> holds three separate Integer objects, one per number, so every number is wrapped in an object. Right: an IntStream holds the plain numbers 72, 85 and 91 side by side with no wrapping, and sum() is ready to use.

Example 1 · Three ways to total marks

MarksTotalDemo.javaJava
import java.util.List;
public class MarksTotalDemo {    public static void main(String[] args) {        List<Integer> marks = List.of(78, 92, 65, 88, 71);
        // a loop: each Integer is unboxed into the int m        int loopTotal = 0;        for (int m : marks) {            loopTotal += m;        }
        // Stream<Integer>: reduce adds boxed Integer objects        int reduceTotal = marks.stream().reduce(0, Integer::sum);
        // IntStream: unbox once with mapToInt, then sum()        int intStreamTotal = marks.stream().mapToInt(Integer::intValue).sum();
        System.out.println("Loop total:      " + loopTotal);        System.out.println("reduce total:    " + reduceTotal);        System.out.println("IntStream total: " + intStreamTotal);    }}
Output
Loop total:      394
reduce total:    394
IntStream total: 394

What this code does

  • All three give the same total. The loop and reduce work on Integer objects; reduce even boxes every partial total again.
  • mapToInt(Integer::intValue) turns the Stream<Integer> into an IntStream of plain int values, and sum() is built in. marks.stream().sum() would not compile, because Stream<Integer> has no sum().
  • Why mapToInt: an IntStream holds plain int values, so there is no boxing, sum() is ready, and the code cannot get the identity of a reduce wrong.

Objects cost more than plain numbers. Each one takes extra memory, and every + must unbox two objects and box the result again. For five marks this does not matter. For a million UPI payments it slows the program down and fills memory with short-lived objects. Stream<Integer> also has no sum() method, because a Stream<T> does not know that T is a number. You would write reduce(0, Integer::sum). The three primitive streams in java.util.stream fix both problems: they hold plain values and they know how to add them.

There is no CharStream, FloatStream or ByteStream. Characters come as an IntStream, and float values go into a DoubleStream.

Moving between object and number streams

Most data starts as objects: a list of students, a list of orders. You pull a number out of each object with mapToInt, mapToLong or mapToDouble. Each takes a lambda or method reference that returns the number, such as Student::marks.

Example 2 · A class report with mapToInt

ClassReportDemo.javaJava
import java.util.List;
record Student(String name, int marks) { }
public class ClassReportDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Aarav", 78),                new Student("Priya", 92),                new Student("Rohan", 65),                new Student("Kavya", 88));
        int total = students.stream().mapToInt(Student::marks).sum();        int highest = students.stream().mapToInt(Student::marks).max().getAsInt();        int lowest = students.stream().mapToInt(Student::marks).min().getAsInt();        double average = students.stream().mapToInt(Student::marks).average().getAsDouble();        long above75 = students.stream().mapToInt(Student::marks).filter(m -> m >= 75).count();
        System.out.println("Total:        " + total);        System.out.println("Highest:      " + highest);        System.out.println("Lowest:       " + lowest);        System.out.println("Average:      " + average);        System.out.println("75 and above: " + above75);    }}
Output
Total:        323
Highest:      92
Lowest:       65
Average:      80.75
75 and above: 3

What this code does

  • mapToInt(Student::marks) pulls the int out of each record. After that, sum, max, min, average and count are all one call each. A stream is single-use, so each line builds a new one.
  • max() gives an OptionalInt and average() gives an OptionalDouble; getAsInt() and getAsDouble() are safe here because the list is never empty. The average 80.75 is a real double, not a cut-off int.

Example 3 · Back to objects with boxed and mapToObj

RollNumbersDemo.javaJava
import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.IntStream;
public class RollNumbersDemo {    public static void main(String[] args) {        int[] rolls = {104, 101, 103, 102};
        List<Integer> sorted = Arrays.stream(rolls).sorted().boxed().toList();        System.out.println("Sorted rolls: " + sorted);
        List<String> labels = Arrays.stream(rolls)                .sorted()                .mapToObj(r -> "Roll " + r)                .toList();        System.out.println("Labels: " + labels);
        String csv = IntStream.of(45, 78, 90)                .mapToObj(String::valueOf)                .collect(Collectors.joining(","));        System.out.println("CSV line: " + csv);    }}
Output
Sorted rolls: [101, 102, 103, 104]
Labels: [Roll 101, Roll 102, Roll 103, Roll 104]
CSV line: 45,78,90

What this code does

  • Arrays.stream(int[]) gives an IntStream. boxed() wraps each int in an Integer, so the result can become a List<Integer>.
  • mapToObj turns each number into any object, here a String. Collectors.joining needs String elements, so the numbers are mapped with String::valueOf first.

To go back from numbers to objects, use boxed(), which turns each int into an Integer, or mapToObj(...), which turns each number into any object you like, such as a String. You need this step before collecting into a List, because IntStream has no collect(Collectors.toList()).

  • list.stream().mapToInt(Student::marks): Stream<Student> to IntStream.
  • IntStream.of(4, 8, 6) and Arrays.stream(intArray): an IntStream straight from numbers or an int[].
  • intStream.boxed(): IntStream to Stream<Integer>; intStream.mapToObj(i -> "Roll " + i): to Stream<String>.
  • intStream.asLongStream() and asDoubleStream(): widen every value to long or double.

sum, average, max and min

On an IntStream, sum() returns an int, and it returns 0 for an empty stream. count() returns a long. These always have an answer.

Example 4 · Trap: sum() overflows on big totals

ShopTotalDemo.javaJava
import java.util.List;
public class ShopTotalDemo {    public static void main(String[] args) {        // one shop's UPI receipts for a day, in paise        List<Integer> receiptsInPaise = List.of(1_500_000_000, 800_000_000, 200_000_000);
        int wrong = receiptsInPaise.stream().mapToInt(Integer::intValue).sum();        long right = receiptsInPaise.stream().mapToLong(Integer::longValue).sum();
        System.out.println("int sum:  " + wrong);        System.out.println("long sum: " + right);        System.out.println("In rupees: " + right / 100);    }}
Output
int sum:  -1794967296
long sum: 2500000000
In rupees: 25000000

What this code does

  • The real total is 2.5 billion paise. An int holds only up to 2,147,483,647, so IntStream.sum() wraps around to a negative number. No error is shown.
  • mapToLong makes a LongStream, and its sum() adds in long, which holds far bigger values. asLongStream() does the same for an IntStream you already have.

max() and min() return an OptionalInt, and average() returns an OptionalDouble. An empty class has no topper and no average, so the result must be able to say "no value". The average is always a double, so there is no integer-division trap: the average of 3 and 4 is 3.5. One trap remains. sum() on an IntStream adds in int, and an int holds values only up to about 2.1 billion. Larger totals overflow: they wrap around to a wrong, often negative, number. For money in paise or big counts, use mapToLong or asLongStream() before sum().

Need sum, min, max, count and average together? summaryStatistics() gives all five in one pass, as in the summarizing lesson of the Collectors module.

Reading an OptionalDouble

An OptionalDouble is a small box that holds either one double or nothing. average() returns one because the average of zero numbers does not exist. Printing it shows OptionalDouble[72.5] or OptionalDouble.empty.

Example 5 · OptionalDouble for an empty day

ShopAverageDemo.javaJava
import java.util.List;import java.util.NoSuchElementException;import java.util.OptionalDouble;
public class ShopAverageDemo {    public static void main(String[] args) {        List<Double> mondayBills = List.of(120.0, 45.5, 60.0, 30.5);        List<Double> sundayBills = List.of();   // shop closed
        OptionalDouble monday = mondayBills.stream().mapToDouble(Double::doubleValue).average();        OptionalDouble sunday = sundayBills.stream().mapToDouble(Double::doubleValue).average();
        System.out.println("Monday: " + monday);        System.out.println("Sunday: " + sunday);        System.out.println("Sunday has a value? " + sunday.isPresent());        System.out.println("Sunday with orElse: " + sunday.orElse(0.0));        monday.ifPresent(a -> System.out.println("Monday average bill: Rs. " + a));        System.out.println("Sunday total: " + sundayBills.stream().mapToDouble(Double::doubleValue).sum());
        try {            sunday.getAsDouble();        } catch (NoSuchElementException e) {            System.out.println("getAsDouble on empty: " + e.getMessage());        }    }}
Output
Monday: OptionalDouble[64.0]
Sunday: OptionalDouble.empty
Sunday has a value? false
Sunday with orElse: 0.0
Monday average bill: Rs. 64.0
Sunday total: 0.0
getAsDouble on empty: No value present

What this code does

  • The average of no bills does not exist, so average() returns OptionalDouble.empty. The sum of no bills does exist: it is 0.0.
  • orElse(0.0) and isPresent() handle the empty case calmly. getAsDouble() on an empty box throws NoSuchElementException, which would crash a report on a holiday.

getAsDouble() takes the value out, but on an empty box it throws NoSuchElementException with the message "No value present". Use it only when the data can never be empty. Otherwise pick one of the safe ways below. OptionalInt from max() works the same way with getAsInt().

  • orElse(0.0): the value, or a default you choose when the box is empty.
  • isPresent(): true when there is a value, so you can print a message such as "No data yet".
  • ifPresent(a -> ...): run some code only when there is a value.
  • getAsDouble(): the value, or an exception when empty.

Next step

Check your understanding

12 quick questions