IntStream, LongStream and DoubleStream
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
Example 1 · Three ways to total marks
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); }}Loop total: 394 reduce total: 394 IntStream total: 394
What this code does
- All three give the same total. The loop and
reducework onIntegerobjects;reduceeven boxes every partial total again. mapToInt(Integer::intValue)turns theStream<Integer>into anIntStreamof plainintvalues, andsum()is built in.marks.stream().sum()would not compile, becauseStream<Integer>has nosum().- Why mapToInt: an
IntStreamholds plainintvalues, 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.
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
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); }}Total: 323 Highest: 92 Lowest: 65 Average: 80.75 75 and above: 3
What this code does
mapToInt(Student::marks)pulls theintout of each record. After that,sum,max,min,averageandcountare all one call each. A stream is single-use, so each line builds a new one.max()gives anOptionalIntandaverage()gives anOptionalDouble;getAsInt()andgetAsDouble()are safe here because the list is never empty. The average 80.75 is a realdouble, not a cut-offint.
Example 3 · Back to objects with boxed and mapToObj
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); }}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 anIntStream.boxed()wraps eachintin anInteger, so the result can become aList<Integer>.mapToObjturns each number into any object, here aString.Collectors.joiningneedsStringelements, so the numbers are mapped withString::valueOffirst.
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>toIntStream.IntStream.of(4, 8, 6)andArrays.stream(intArray): anIntStreamstraight from numbers or anint[].intStream.boxed():IntStreamtoStream<Integer>;intStream.mapToObj(i -> "Roll " + i): toStream<String>.intStream.asLongStream()andasDoubleStream(): widen every value tolongordouble.
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
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); }}int sum: -1794967296 long sum: 2500000000 In rupees: 25000000
What this code does
- The real total is 2.5 billion paise. An
intholds only up to 2,147,483,647, soIntStream.sum()wraps around to a negative number. No error is shown. mapToLongmakes aLongStream, and itssum()adds inlong, which holds far bigger values.asLongStream()does the same for anIntStreamyou 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().
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
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()); } }}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()returnsOptionalDouble.empty. The sum of no bills does exist: it is 0.0. orElse(0.0)andisPresent()handle the empty case calmly.getAsDouble()on an empty box throwsNoSuchElementException, 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():truewhen 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