What is The Difference Between Collections and Streams in Java?

Let’s start by describing what a Stream is in Java 8. Streams let you manipulate collections of data without you explicitly iterating over them. In other words, a Stream is a sequence of elements from a source that supports data processing operations.

The biggest difference is:

Streams allow Pipelining:

Many Streams return a Stream themselves, which allow chaining of operation and forming a pipeline. A pipeline of operations in Java 8 can be seen as a database-like query:

List transactionsIds = 
    transactions.stream()
                .filter(t -> t.getType() == Transaction.GROCERY)
                .sorted(comparing(Transaction::getValue).reversed())
                .map(Transaction::getId)
                .collect(toList());

Whereas, for collections, this is quite different and lengthy in code:

List groceryTransactions = new Arraylist<>();
for(Transaction t: transactions){
  if(t.getType() == Transaction.GROCERY){
    groceryTransactions.add(t);
  }
}
Collections.sort(groceryTransactions, new Comparator(){
  public int compare(Transaction t1, Transaction t2){
    return t2.getValue().compareTo(t1.getValue());
  }
});
List transactionIds = new ArrayList<>();
for(Transaction t: groceryTransactions){
  transactionsIds.add(t.getId());
}

Elements in Streams are Lazily loaded.

Meaning as soon as some data is available, processing those elements starts and the process does not need to wait until all the data elements are loaded in memory. However, all elements of Collections should be loaded in memory before processing starts.

Their Internal iteration over their elements.

Contrary to collections, which are iterated explicitly using an iterator, stream operations do the iteration for you. And you don’t have to write cumbersome For-Each codes.
Please note that a common characteristic that both collection and stream have is that you can traverse them only once. Meaning, if you use an iterator to traverse your list, you have to create a new iterator if you want to loop through it again:

List list = Arrays.asList(1,2,3,4,5);
Stream stream = list.stream();
s.forEach(x->x*2);
s.forEach(x->x+1); // <<< This will throw an IllegalStateException

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *