Streams Versus Collections

Both are the old and new notions of  interfaces to a sequence of elements. So what’s the difference? In a nutshell, collections are about data and streams are about computations.

Now imagine, when a movie is being streamed over internet. It is now a stream. The streaming video player needs to have downloaded only a few frames in advance of where the user is watching.

Below text from Oracle.com

In the coarsest terms, the difference between collections and streams has to do with when things are computed.

A collection is an in-memory data structure, which holds all the values that the data structure currently has—every element in the collection has to be computed before it can be added to the collection.

In contrast, a stream is a conceptually fixed data structure in which elements are computed on demand.

Now remember our Employee class!!

public class Employee { 
    private int empId; 
    private String empName; 
    private String gender; 
    private String salary; 
    // and their getters/setters 
}

Say we have a List of 100 Employees and we need their Employee Ids.

In Collection way:

List<Integer> employeeIds = new ArrayList<>();

for(Employee emp: employees ){
 employeeIds .add(emp.getEmpId())); 
}

 

In Stream way:

List<Integer> employeeIds = employees.stream()
                            .map(Employee::getId).collect(toList());

 

If you notice, in Collection way, we are explicitly iterating over Employee List sequentially and adding empId. In contrast, when using a stream, there’s no explicit iteration.

The code in, Stream way, builds a query, where the map operation is parameterized to extract the employeeIds and then collect operation converts the resulting Stream into a List.

 

Hope this clears your doubt!!