Friday, November 9, 2018

Java 8 - Streams - Numeric Streams


It is common to have numeric operations min, max, sum in our code. Stream interface have min and max methods but doesn't have sum method because it make no sense to have it.
Even though we can have sum operation using reduce() it has unboxing cost. This is same for min, max operations.
Considering those factors, Stream API provides separate interfaces for primitives. IntStream, LongStream and DoubleStream.

Convert to numeric stream

stream.mapToInt() - return IntStream
stream.mapToLong() - return LongStream
stream.mapToDoulbe() - return DoubleStream

IntStream intStream = stream.mapToInt()

Convert back to stream of objects


String<Integer> = intStream.boxed()

Optional values

For primitive operations Optional also have corresponding primitive optionals.
OptionalInt, OptionalLong, OptionalDouble

There are corresponding functional interfaces like IntPredicate, IntConsumer, IntUnaryOperator for numeric operations.


import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;
import java.util.OptionalInt;

public class NumericApp {

    public static void main(String[] args) {
        List<Subject> subjects = Arrays.asList(
                Subject.newInstance("Maths", 95), Subject.newInstance("Enlighs", 98),
                Subject.newInstance("Music", 70), Subject.newInstance("Science", 84),
                Subject.newInstance("History", 92));
        int total =;
        OptionalInt min =;
        OptionalInt max =;
        OptionalDouble average =;
        System.out.println("total: " + total);
        System.out.println("min: " + min);
        System.out.println("max: " + max);
        System.out.println("average: " + average);


public class Subject {

    private String name;
    private Integer marks;

    private Subject(String name, Integer marks) { = name;
        this.marks = marks;
    public static Subject newInstance(String name, Integer marks) {
        return new Subject(name, marks);

    public String getName() {
        return name;

    public Integer getMarks() {
        return marks;


No comments:

Post a Comment