Difference between Streams and Collections in Java 8

JavaServer Side ProgrammingProgramming

Java Collections framework is used for storing and manipulating group of data. It is an in-memory data structure and every element in the collection should be computed before it can be added in the collections.

Stream API is only used for processing group of data. It does not modify the actual collection, they only provide the result as per the pipelined methods.

Sr. No.KeyCollectionsStreams
1
Basic
It is used for storing and manipulating group of data
Stream API is only used for processing group of data
2
Package
All the classes and interfaces of this API is in the Java.util package
All the classes and interfaces of this API is in the java.util.stream  package
3
Eager/Lazy
All the elements in the collections are computed in the beginning.
In streams, intermediate operations are lazy.
4.
Data Modification
In collections, we can remove or add elements.
We can’t modify streams.
5
External /Internal iterator
Collections perform iteration over the collection.
Stream perform iteration   internally.

Example of Collections

public class CollectiosExample {
   public static void main(String[] args) {

      List<String> laptopList = new ArrayList<>();
      laptopList.add("HCL");
      laptopList.add("Apple");
      laptopList.add("Dell");
      Comparator<String> com = (String o1, String o2)->o1.compareTo(o2);

      Collections.sort(laptopList,com);

      for (String name : laptopList) {
         System.out.println(name);
      }
   }
}

Example of Streams

public class StreamsExample {
   public static void main(String[] args) {

      List<String> laptopList = new ArrayList<>();
      laptopList.add("HCL");
      laptopList.add("Apple");
      laptopList.add("Dell");
      laptopList.stream().sorted().forEach(System.out::println);
   }
}
raja
Published on 09-Sep-2020 09:30:04
Advertisements