Skip to main content

Java Stream API

Updated 12 min readMarkdown
Part of seriesJava 8 Overview & Key Features
Java Stream API

What is the Java Stream API?

Stream API provides a functional style mechanism for processing sequence of elements. It is introduced in Java 8(java.util.stream). A stream is NOT a data structure, it does not store data. Instead it conveys elements from source(Collection, Array, IO channel, generator function) through a pipeline of operations.

Collections are about data storage. Streams are about data computation. Streams are consumed once; you can not reuse a closed stream - you must create a new one.

Stream Characteristics

Characteristics Description Example Impact
Non-storage Stream does not hold data Original collection is unchanged after stream processing
Functional in nature Operations produce new streams, source is not modified. stream.filter() returns new stream.
Laziness-seeking Intermediate ops are lazy, execute only when terminal operation is called. filter() + map() runs together, not separately.

Stream Pipeline Structure

Every stream pipeline has three parts:

  • Source - Where the stream originates (Collection, array, Stream.of(), Stream.generate(), Files.lines() etc).

  • Intermediate Operations - lazy transformations that returns a new Stream (filter, map, sorted, distinct, limit etc.)

  • Terminal Operations - triggers the pipeline, produces a result or side-effect (collect, forEach, reduce, count, findFirst etc.)

employeeList.stream() //source
        .filter(x-> x.yearOfJoining > 2015) //Intermediate Operation
        .map(Employee::getName)  //Intermediate Operation
        .forEach(System.out::println); //terminal operation

Ways to Create a Stream

Method Example Use Case
Collection.stream() list.stream() Most common; from any collection
Collection.parallelStream() list.parallelStream() Parallel processing stream
Stream.of() Stream.of(1,2,3) or Stream.of(arr) From known elements or array
Arrays.stream() Arrays.stream(intArray) Primitive or object arrays
Stream.iterate() Stream.iterate(0,n->n+2) Infinite ordered stream
Stream.generate() Stream.generate(Math::random) infinite unordered stream
IntStream.range() IntStream.range(0,10) Primitive int range
Files.lines() Files.lines(Path.of(text.txt)) Line by Line file reading
Pattern.splitAsStream() pattern.splitAsStream(str) Regex-split stream
Stream.concat() Stream.concat(s1,s2) merge two streams lazily

Stream operations accepts functional interfaces as argument, will cover this in separate blog post.

Stream Intermediate Operations

All intermediate operations return a stream. They build up a pipeline and do NOT execute until a terminal operation is called, this is called as LAZY EVALUATION.

Filtering & Slicing Intermediate Operations

Operation Signature Description Example
filter filter(Predicate) keep matching elements filter(s-> s.startsWith("A"))
distinct distinct() Removes duplicates - uses equals and hashcode method distinct()
limit limit(long n) Truncate to first n elements) limit(5)
skip skip(long n) discard first n elements skip(10)
takeWhile takeWhile(Predicate) - Java 9 Take while predicate is true, stop at first false takeWhile(n->n<10)
dropWhile dropWhile(Predicate) Drop while predicate is true, keeps rest. dropWhile(n-> n<10)

Mapping Operations

Operation Description Return Type Example
map(Function) Transforms each element into another object Stream map(String::toUpperCase)
mapToInt(ToIntFunction) Map to IntStream IntStream mapToInt(String::length)
mapToLong(ToLongFunction) Map to LongStream LongStream mapToLong(File::length)
mapToDouble(ToDoubleFunction) Map to DoubleStream DoubleStream mapToDouble(Product::getPrice)
flatMap(Function<T,Stream>) Flatten nested stream into one Stream flatMap(Collection::stream)
flatMapToInt flatten to IntStream IntStream flatMapToInt(arr->Arrays.stream(arr))
mapMulti - java16 Imperative flatmapping with consumer Stream mapMulti((e,buf)->buf.accept(e.name))
//scenario1: List<List<Integer>>  --> List<Integer> (flatten)
List<List<Integer>> nested = Arrays.asList(Arrays.asList(1,2),Arrays.asList(3,4),Arrays.asList(5,6));
        List<Integer> list = nested.stream()
                .flatMap(Collection::stream)
                .collect(Collectors.toList());

//scenario2: get all words in a list of sentences
 List<String> words =  sentences.stream()
                .flatMap(List::stream)
                .flatMap(s-> Arrays.stream(s.split(" ")))
                .collect(Collectors.toList());

Sorting & Picking

  • sorted() - natural order (element must implement Comparator)

  • sorted(Comparator) - custom order using Comparator

  • peek(Consumer) - perform side effect without consuming stream for debugging

Terminal Operations

Collecting

collect() is the most powerful terminal operation. It uses a Collector to accumulate stream elements into a result container.

Built In Collectors

Collector Return Type Description
toList() List Mutable List(order preserved)
toUnmodifiableList - Java10 List Immutable List
toSet() Set Unordered, no dupes
toCollection(Supplier) Collection Custom collection TreeSet::new
toMap(keyMapper,valueMapper) Map<K,V> Throws exception on dupe keys
toMap(keyMapper,valueMapper,mergeFunction) Map<K,V> Resolves Dupe keys
toConcurrentMap(...) ConcurrentMap<K,V> Thread safe Map
groupingBy(Function) Map<K,List> Group by classifier
groupingBy(Function, Collector) Map<K,D> Group + downstream collector
partitioningBy(Predicate) Map<Boolean,List> two groups true/false
counting() Long Count of elements
summingInt/Long/Double numeric Sum of mapped values
averagingInt/Long/Double Double average of mapped values
summarizingInt IntSummaryStatistics count,sum,min,max,avg
joining() String concatenated strings
joining(delimiter) String with separator
joining(delimiter,prefix,suffix) String Full control
mapping(Function,Collector) depends Transform then collect
teeing(c1,c2,BiFunction) - Java12 R two collectors, merge results
collectingAndThen(Collector,Function) R post-process a collector result
mixBy(Comparator) //maxBy Optional Min/Max element

Reduce Operations

Operation Description Example
reduce(BinaryOperator) Reduce with no identify reduce(Integer::sum)
reduce(T identify,BinaryOperator) Reduce with identify reduce(0,Integer::sum)
reduce(identify,BiFunction,BinaryOperator) Reduce to different type reduce(0L,(acc,ele)->acc+e.length(),Long::sum)
count() number of elements stream.count()
sum() (primitive streams) sum of numeric stream intStream.sum()
min(Comparator) minimum element min(Comparator.naturalOrder())
max(Comparator) maximum element max(Comparator.comparingInt(String::length))
findFirst() first element of stream findFirst()
findAny() Any element(better for parallel) findAny()
anyMatch(Predicate) Any element matches anyMatch(s->s.isEmpty())
allMatch(Predicate) All element match allMatch(n->n>0)
noneMatch(predicate) No elements match noneMatch(String::isEmpty)
forEach(Consumer) iterate with side effects forEach(System.out::println)
forEachOrdered(Consumer) Ordered iteration(parallel-safe) forEachOrdered(System.out::println)
toArray() Convert stream to array toArray(Employee::new)

Code

Lets create Employee model class

public class Employee {

    int empId;
    String empName;
    int empAge;
    String empGender;
    String empDepartment;
    int empYearOfJoining;
    double empSalary;

    public Employee(int empId, String empName, int empAge, String empGender, String empDepartment, int empYearOfJoining, double empSalary) {
        this.empId = empId;
        this.empName = empName;
        this.empAge = empAge;
        this.empGender = empGender;
        this.empDepartment = empDepartment;
        this.empYearOfJoining = empYearOfJoining;
        this.empSalary = empSalary;
    }

    public int getEmpId() {
        return empId;
    }

    public String getEmpName() {
        return empName;
    }

    public int getEmpAge() {
        return empAge;
    }

    public String getEmpGender() {
        return empGender;
    }

    public String getEmpDepartment() {
        return empDepartment;
    }

    public int getEmpYearOfJoining() {
        return empYearOfJoining;
    }

    public double getEmpSalary() {
        return empSalary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "empId=" + empId +
                ", empName='" + empName + '\'' +
                ", empAge=" + empAge +
                ", empGender='" + empGender + '\'' +
                ", empDepartment='" + empDepartment + '\'' +
                ", empYearOfJoining=" + empYearOfJoining +
                ", empSalary=" + empSalary +
                '}';
    }
}

setup main class with employees data to perform Stream API operations

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

        ArrayList<Employee> employeeList = new ArrayList<>();

        employeeList.add(new Employee(288, "Riya Desai", 29, "Female", "HR", 2017, 24000.0));
        employeeList.add(new Employee(299, "Karan Mehta", 34, "Male", "Sales And Marketing", 2013, 16800.0));
        employeeList.add(new Employee(300, "Priya Nair", 26, "Female", "Product Development", 2019, 30500.0));
        employeeList.add(new Employee(311, "David Cruz", 41, "Male", "Security And Transport", 2011, 12000.0));
        employeeList.add(new Employee(322, "Sneha Pillai", 28, "Female", "Account And Finance", 2016, 22100.0));
        employeeList.add(new Employee(333, "Omar Sheikh", 36, "Male", "Infrastructure", 2010, 19500.0));
        employeeList.add(new Employee(344, "Fatima Malik", 25, "Female", "Sales And Marketing", 2020, 13200.0));
        employeeList.add(new Employee(355, "Rohan Verma", 30, "Male", "Product Development", 2015, 33800.0));
        employeeList.add(new Employee(366, "Lena Fischer", 27, "Female", "HR", 2018, 23500.0));
        employeeList.add(new Employee(377, "Arjun Kapoor", 45, "Male", "Account And Finance", 2009, 41000.0));
        employeeList.add(new Employee(388, "Mei Wong", 23, "Female", "Sales And Marketing", 2021, 11800.0));
        employeeList.add(new Employee(399, "Samuel Osei", 33, "Male", "Infrastructure", 2014, 20300.0));
        employeeList.add(new Employee(400, "Divya Menon", 29, "Female", "Product Development", 2017, 31200.0));
        employeeList.add(new Employee(411, "Tariq Hassan", 38, "Male", "Security And Transport", 2012, 13700.5));
        employeeList.add(new Employee(422, "Anika Sharma", 24, "Female", "HR", 2020, 21500.0));
        employeeList.add(new Employee(433, "Lucas Petrov", 31, "Male", "Product Development", 2016, 36400.0));
        employeeList.add(new Employee(444, "Zara Qureshi", 26, "Female", "Account And Finance", 2019, 22800.0));
        employeeList.add(new Employee(455, "Vikram Singh", 40, "Male", "Sales And Marketing", 2011, 18500.0));
        employeeList.add(new Employee(466, "Hana Yoshida", 28, "Female", "Infrastructure", 2018, 17200.0));
        employeeList.add(new Employee(477, "Ethan Brooks", 35, "Male", "Security And Transport", 2013, 14100.5));
    
        
    }
}

Different Scenarios

Scenario 1 : How many male and female employees are there in the organization?

Map<String,Long> diversity = employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getEmpGender,Collectors.counting()));

        Set<Map.Entry<String,Long>> entry = diversity.entrySet();

        for (Map.Entry<String,Long> e : entry){
            System.out.println(e.getKey()+" - "+e.getValue());
        }

output

Male - 10
Female - 10

scenario 2: Print the name of all employees in the organization?

List<String> list = employeeList.stream()
                .map(Employee::getEmpName)
                .collect(Collectors.toList());
        System.out.println(list);

output

[Riya Desai, Karan Mehta, Priya Nair, David Cruz, Sneha Pillai, Omar Sheikh, Fatima Malik, Rohan Verma, Lena Fischer, Arjun Kapoor, Mei Wong, Samuel Osei, Divya Menon, Tariq Hassan, Anika Sharma, Lucas Petrov, Zara Qureshi, Vikram Singh, Hana Yoshida, Ethan Brooks]

scenario 3: Print the name of all departments in the organization?

employeeList.stream()
                .map(Employee::getEmpDepartment)
                .distinct()
                .forEach(System.out::println);

output

HR
Sales And Marketing
Product Development
Security And Transport
Account And Finance
Infrastructure

scenario 4 What is the average age of male and female employees?

Map<String,Double> avgAge = employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getEmpGender,Collectors.averagingDouble(Employee::getEmpAge)));

        Set<Map.Entry<String,Double>> ageEntry = avgAge.entrySet();
        for (Map.Entry<String,Double> e: ageEntry){
            System.out.println(e.getKey()+" - "+e.getValue());
        }

output

Male - 36.3
Female - 26.5

scenario 5: Get the details of highest paid employee in the organization?

Optional<Employee> empDetails = employeeList.stream()
                .max(Comparator.comparingDouble(Employee::getEmpSalary));

System.out.println(empDetails.get());

output

Employee{empId=377, empName='Arjun Kapoor', empAge=45, empGender='Male', empDepartment='Account And Finance', empYearOfJoining=2009, empSalary=41000.0}

Scenario 6: Get the names of all employees who have joined after 2016?

List<Employee> joinedAfter2016 = employeeList.stream()
                .filter(e -> e.empYearOfJoining > 2016)
                .collect(Collectors.toList());

        for (Employee e: joinedAfter2016){
            System.out.println(e.empName+" joined org in year - "+ e.empYearOfJoining );
        }

//To get only names, above code is for validation
 employeeList.stream()
                .filter(e  -> e.empYearOfJoining > 2016)
                .map(Employee::getEmpName)
                .forEach(System.out::println);

output

Riya Desai joined org in year - 2017
Priya Nair joined org in year - 2019
Fatima Malik joined org in year - 2020
Lena Fischer joined org in year - 2018
Mei Wong joined org in year - 2021
Divya Menon joined org in year - 2017
Anika Sharma joined org in year - 2020
Zara Qureshi joined org in year - 2019
Hana Yoshida joined org in year - 2018

Scenario 7: Count the number of employees in each department?

Map<String,Long> deptWiseCount = employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getEmpDepartment,Collectors.counting()));

        Set<Map.Entry<String,Long>> entrySet = deptWiseCount.entrySet();
        for (Map.Entry<String,Long> e: entrySet){
            System.out.println(e.getKey()+" - "+e.getValue());

output

Product Development - 4
Security And Transport - 3
Sales And Marketing - 4
Infrastructure - 3
HR - 3
Account And Finance - 3

scenario 8: What is the average salary of each department?

Map<String,Double> avgDeptWiseSalary =  employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getEmpDepartment,Collectors.averagingDouble(Employee
                ::getEmpSalary)));

        Set<Map.Entry<String, Double>> avgSalaryEntrySet = avgDeptWiseSalary.entrySet();
        for (Map.Entry<String,Double> e: avgSalaryEntrySet){
            System.out.println(e.getKey()+" - "+e.getValue());
        }

output

Product Development - 32975.0
Security And Transport - 13267.0
Sales And Marketing - 15075.0
Infrastructure - 19000.0
HR - 23000.0
Account And Finance - 28633.333333333332

Scenario 9: Get the details of youngest female employee in the Account And Finance department?

Optional<Employee> youngestFemaleEmpInHRDept = employeeList.stream()
                .filter(e-> e.empDepartment.equals("Account And Finance"))
                .filter(e-> e.empGender.equals("Female"))
                .min(Comparator.comparingInt(Employee::getEmpAge));

        System.out.println(youngestFemaleEmpInHRDept.get());

output

Employee{empId=444, empName='Zara Qureshi', empAge=26, empGender='Female', empDepartment='Account And Finance', empYearOfJoining=2019, empSalary=22800.0}

Scenario 10: Who has the most working experience in the organization?

Optional<String> emp = employeeList.stream()
                .min(Comparator.comparingInt(Employee::getEmpYearOfJoining))
                .map(Employee::getEmpName);

        System.out.println(emp.get());

output

Arjun Kapoor

Scenario 11: How many male and female employees are there in the sales and marketing team?

Map<String,Long> salesEmployees = employeeList.stream()
                .filter(e-> e.empDepartment.equals("Sales And Marketing"))
                .collect(Collectors.groupingBy(Employee::getEmpGender,Collectors.counting()));

        Set<Map.Entry<String,Long>> entrySet = salesEmployees.entrySet();
        for (Map.Entry<String,Long> es : entrySet){
            System.out.println(es.getKey()+" - "+es.getValue());
        }

output

Female - 2
Male - 2

scenario 12: What is the average salary of male and female employees?

Map<String,Double> eSalaryAvg = employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getEmpGender,Collectors.averagingDouble(Employee::getEmpSalary)));

        Set<Map.Entry<String,Double>> eSalaryEntrySet = eSalaryAvg.entrySet();
        for (Map.Entry<String,Double> es: eSalaryEntrySet){
            System.out.println(es.getKey()+" - "+es.getValue());
        }

output

Male - 22610.1
Female - 21780.0

scenario 13: List down the names of all employees in each department?

Map<String,List<Employee>> deptWiseEmp = employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getEmpDepartment));

        Set<Map.Entry<String,List<Employee>>> deptEntrySet = deptWiseEmp.entrySet();
        for (Map.Entry<String,List<Employee>> e : deptEntrySet){
            System.out.println("----"+e.getKey()+"-----");
            List<Employee> emp = e.getValue();
            for (Employee eachEmp : emp){
                System.out.println(eachEmp.empName);
            }
        }

output

----Product Development-----
Priya Nair
Rohan Verma
Divya Menon
Lucas Petrov
----Security And Transport-----
David Cruz
Tariq Hassan
Ethan Brooks
----Sales And Marketing-----
Karan Mehta
Fatima Malik
Mei Wong
Vikram Singh
----Infrastructure-----
Omar Sheikh
Samuel Osei
Hana Yoshida
----HR-----
Riya Desai
Lena Fischer
Anika Sharma
----Account And Finance-----
Sneha Pillai
Arjun Kapoor
Zara Qureshi

scenario 14: What is the average salary and total salary of the whole organization?

DoubleSummaryStatistics eStats = employeeList.stream()
         .collect(Collectors.summarizingDouble(Employee::getEmpSalary));

System.out.println("avr salary: "+eStats.getAverage());
System.out.println("total salary paid by org: "+eStats.getSum());

output

avr salary: 22195.05
total salary paid by org: 443901.0

scenario 15: Separate the employees who are younger or equal to 25 years from those employees who are older than 30 years.

Map<Boolean,List<Employee>> age25ormore = employeeList.stream()
                .collect(Collectors.partitioningBy(e-> e.empAge > 30));

        Set<Map.Entry<Boolean,List<Employee>>> ageSet = age25ormore.entrySet();
        for (Map.Entry<Boolean,List<Employee>> set: ageSet){
            if (set.getKey()){
                System.out.println("Employees age is more than 30");
            }else {
                System.out.println("Employee age is equals or less than 30");
            }
            List<Employee> empList = set.getValue();
            for (Employee e : empList){
                System.out.println(e.empName);
            }
        }

output

Employee age is equals or less than 30
Riya Desai
Priya Nair
Sneha Pillai
Fatima Malik
Rohan Verma
Lena Fischer
Mei Wong
Divya Menon
Anika Sharma
Zara Qureshi
Hana Yoshida
Employees age is more than 30
Karan Mehta
David Cruz
Omar Sheikh
Arjun Kapoor
Samuel Osei
Tariq Hassan
Lucas Petrov
Vikram Singh
Ethan Brooks

No comments yet. Be the first to comment.