The Wayback Machine - https://web.archive.org/web/20240930170021/https://www.geeksforgeeks.org/difference-between-streams-and-collections-in-java/
Open In App

Difference Between Streams and Collections in Java

Last Updated : 07 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 we add it to the Collection. Operations such as searching, sorting, insertion, manipulation, and deletion can be performed on a Collection. It provides many interfaces like (Set, List, Queue, Deque) and Classes like (ArrayList, Vector, LinkedList, PriorityQueue, HashSet).

Difference-Between-Streams-and-Collections-in-Java

On the other hand, IStream is an API that is introduced in Java 8 which is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The Stream API is used to process collections of objects.

Main features of the Java stream are as follows:

  • A stream is not a data structure instead it takes input from the Collections, Arrays, or I/O channels.
  • Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
  • Each intermediate operation is lazily executed and returns another stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.

Example 1: Collections

Java




// Java Program to Illustrate Collection
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GfG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an instance of list
        List<String> companyList = new ArrayList<>();
 
        // Adding elements using add() method
        companyList.add("Google");
        companyList.add("Apple");
        companyList.add("Microsoft");
 
        // Now creating a comparator
        Comparator<String> com
            = (String o1, String o2) -> o1.compareTo(o2);
 
        // Sorting the list
        Collections.sort(companyList, com);
 
        // Iterating using for each loop
        for (String name : companyList) {
 
            // Printing the elements
            System.out.println(name);
        }
    }
}


Output

Apple
Google
Microsoft

 Example: Streams

Java




// Java Program to Demonstrate streams
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty Arraylist
        List<String> companyList = new ArrayList<>();
 
        // Adding elements to above ArrayList
        companyList.add("Google");
        companyList.add("Apple");
        companyList.add("Microsoft");
 
        // Sorting the list
        // using sorted() method and
        // printing using for-each loop
        companyList.stream().sorted().forEach(
            System.out::println);
    }
}


Output

Apple
Google
Microsoft

Let us tabulate the difference between them which is as follows:

    STREAMS        

  COLLECTIONS          

It doesn’t store data, it operates on the source data structure i.e collection. It stores/holds all the data that the data structure currently has in a particular data structure like Set, List or Map,
They use functional interfaces like lambda which makes it a good fit for programming language. Don’t use functional interfaces.
Java Streams are consumable i.e; to traverse the stream, it needs to be created every time. Non-consumable i.e; can be traversable multiple times without creating it again.
Java streams support both sequential and parallel processing. Supports parallel processing and parallel processing can be very helpful in achieving high performance.
All the Java stream API interfaces and classes are in java.util.stream package. Specific classes for primitive types such as IntStream, LongStream, and DoubleStream are used in collections since primitive data types such as int, long in the collections using auto-boxing and these operations could take a lot of time.
Streams are not modifiable i.e one can’t add or remove elements from streams. These are modifiable i.e one can easily add to or remove elements from collections.
Streams are iterated internally by just mentioning the operations. Collections are iterated externally using loops.


Previous Article
Next Article

Similar Reads

Difference between Traditional Collections and Concurrent Collections in java
We all know about Traditional Collections ( i.e. List, Set, Queue and its implemented Classes) and Concurrent Collection (i.e. ConcurrentMap interface, ConcurrentHashMap class, CopyOnWriteArrayList class etc). In these two Collections, there are few differences like: Most of the Classes which are present in Traditional Collections (i.e ArrayList, L
3 min read
Using Guava's Collectors for Collecting Streams to Immutable Collections in Java
Guava is a set of core libraries from Google that includes new collection types. For example, we multimap and multisets, immutable collections, a graph library, and utilities for concurrency. It is used by many companies. In this article, we are going to see how to use Guava's Collectors for Collecting Streams to Immutable Collections in Java. To u
3 min read
Difference Between next() and hasNext() Method in Java Collections
In Java, objects are stored dynamically using objects. Now in order to traverse across these objects is done using a for-each loop, iterators, and comparators. Here will be discussing iterators. The iterator interface allows visiting elements in containers one by one which indirectly signifies retrieval of elements of the collection in forwarding d
3 min read
How to Execute SQL File with Java using File and IO Streams?
In many cases, we often find the need to execute SQL commands on a database using JDBC to load raw data. While there are command-line or GUI interfaces provided by the database vendor, sometimes we may need to manage the database command execution using external software. In this article, we will learn how to execute an SQL file containing thousand
5 min read
Java streams counting() method with examples
In Java 8, there is predefined counting() method returned by Collectors class counting() method to count the number of elements in a Stream. Syntax : public static Collector counting() Where, output is a Collector, acting on a Stream of elements of type T, with its finisher returning the ‘collected’ value of type Long. It is a terminal operation wh
2 min read
Java 8 Streams | Collectors.joining() method with Examples
The joining() method of Collectors Class, in Java, is used to join various elements of a character or string array into a single string object. This method uses the stream to do so. There are various overloads of joining methods present in the Collector class. The class hierarchy is as follows: java.lang.Object ↳ java.util.stream.Collectorsjoining(
8 min read
What is Java Parallel Streams?
Java Parallel Streams is a feature of Java 8 and higher, meant for utilizing multiple cores of the processor. Normally any java code has one stream of processing, where it is executed sequentially. Whereas by using parallel streams, we can divide the code into multiple streams that are executed in parallel on separate cores and the final result is
4 min read
Why You Need to Close the Java Streams in Finally Block?
In Java finally block is a block used to execute important and common code. The finally block is mostly used during exception handling with try and catch to close streams and files. The code in finally block is executed irrespective of whether there is an exception or not. This ensures that all the opened files are properly closed and all the runni
2 min read
Comparing Streams to Loops in Java
A stream is an ordered pipeline of aggregate operations(filter(), map(), forEach(), and collect()) that process a (conceptually unbounded) sequence of elements. A stream pipeline consists of a source, followed by zero or more intermediate operations; and a terminal operation. An aggregate operation performs a function. Ideally, a function's output
7 min read
Streams on Arrays in Java 8
In this article, we would be going through stream method of Arrays class which is added in Java 8, it simplifies many operations on arrays as well have improved the efficiency. Addition of different features like lambdas and streams in java 8 have made java efficient to write elegant code which have improve the readability providing increase in eff
7 min read
Java.util.Collections.frequency() in Java
The method is a java.util.Collections class method. It counts the frequency of the specified element in the given list. It override the equals() method to perform the comparison to check if the specified Object and the Object in the list are equal or not. Syntax: public static int frequency(Collection c, Object o) parameters: c: Collection in which
2 min read
Java.util.Collections.rotate() Method in Java with Examples
java.util.Collections.rotate() method is present in java.util.Collections class. It is used to rotate the elements present in the specified list of Collection by a given distance. Syntax: public static void rotate(List< type > list, int distance) Parameters : list - the list to be rotated. distance - the distance to rotate the list. type - Ty
2 min read
Java.util.Collections.disjoint() Method in java with Examples
java.util.Collections.disjoint() method is present in java.util.Collections class. It is used to check whether two specified collections are disjoint or not. More formally, two collections are disjoint if they have no elements in common. Syntax: public static boolean disjoint(Collection<?> c1, Collection<?> c2) Parameters : c1 - a colle
3 min read
Difference between queue.queue vs collections.deque in Python
Both queue.queue and collections.deque commands give an idea about queues in general to the reader but, both have a very different application hence shouldn't be confused as one. Although they are different and used for very different purposes they are in a way linked to each other in terms of complete functionality. Before we jump into what they a
3 min read
Apache Kafka Streams - Simple Word Count Example
Kafka Streams is used to create apps and microservices with input and output data stored in an Apache Kafka cluster. It combines the advantages of Kafka's server-side cluster technology with the ease of creating and deploying regular Java and Scala apps on the client side. Approach In this article, we are going to use Kafka streams for counting wor
5 min read
What is Apache Kafka Streams?
Kafka Streams is a library for processing and analyzing data stored in Kafka. It expands on crucial stream processing ideas such as clearly separating event time from processing time, allowing for windows, and managing and querying application information simply but effectively in real time. Kafka Streams has a low entry barrier since it is easy to
4 min read
Java Collections Interview Questions and Answers
Java Collection Framework was introduced in JDK 1.2 which contains all the collection classes and interfaces. Java Collection is a framework that provides a mechanism to store and manipulate the collection of objects. It allows developers to access prepackaged data structures and algorithms for manipulating data. Here, we've covered the 50+ Java Co
15+ min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Collections checkedMap() method in Java with Examples
The checkedMap() method of Collections class been present inside java.util package is used to return a dynamically typesafe view of the specified map. The returned map will be serializable if the specified map is serializable. Since null is considered to be a value of any reference type, the returned map permits the insertion of null keys or values
3 min read
Need of Concurrent Collections in java
As we already know Collections which is nothing but collections of Objects where we deals with the Objects using some pre-defined methods. But There are several problems which occurs when we use Collections concept in multi-threading. The problems which occurs while using Collections in Multi-threaded application: Most of the Collections classes ob
2 min read
Collections singletonMap() method in Java with Examples
The singletonMap() method of java.util.Collections class is used to return an immutable map, mapping only the specified key to the specified value. The returned map is serializable. Syntax: public static Map singletonMap(K key, V value) Parameters: This method takes the following parameters as a argument: key - the sole key to be stored in the retu
2 min read
Collections min() method in Java with Examples
min(Collection<? extends T> coll) The min() method of java.util.Collections class is used to return the minimum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements in the collection must be mutually comparable (tha
4 min read
Collections.nCopies() in Java
The role of Collections.nCopies() is to return an immutable list which contains n copies of given object. This function helps if we want to create a list with n copies of given object. The newly allocated data object is tiny i.e, it contains a single reference to the data object. Syntax : public static <T> List<T> nCopies(int number, T
2 min read
Collections max() method in Java with Examples
max(Collection<? extends T> coll) The max() method of java.util.Collections class is used to return the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements in the collection must be mutually comparable (tha
5 min read
Java Lambda Expression with Collections
In this article, Lambda Expression with Collections is discussed with examples of sorting different collections like ArrayList, TreeSet, TreeMap, etc. Sorting Collections with Comparator (or without Lambda): We can use Comparator interface to sort, It only contains one abstract method: - compare(). An interface that only contains only a single abst
3 min read
Collections addAll() method in Java with Examples
The addAll() method of java.util.Collections class is used to add all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under
3 min read
Collections asLifoQueue() method in Java with Examples
The asLifoQueue() method of java.util.Collections class is used to return a view of a Deque as a Last-in-first-out (Lifo) Queue. Method add is mapped to push, remove is mapped to pop and so on. This view can be useful when you would like to use a method requiring a Queue but you need Lifo ordering.Each method invocation on the queue returned by thi
2 min read
Collections checkedCollection() method in Java with Examples
The checkedCollection() method of java.util.Collections class is used to return a dynamically typesafe view of the specified collection. The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object's equals and hashCode methods. This is necessary to preserve the contracts of these
3 min read
Collections checkedList() method in Java with Examples
The checkedList() method of Collections class is present inside java.util package is used to return a dynamically typesafe view of the specified list. The key thing to note here is that the returned list will be serializable if the specified list is serializable. Since null is considered to be a value of any reference type, the returned list permit
3 min read
Collections checkedSet() method in Java with Examples
The checkedSet() method of java.util.Collections class is used to return a dynamically typesafe view of the specified set.The returned set will be serializable if the specified set is serializable.Since null is considered to be a value of any reference type, the returned set permits insertion of null elements whenever the backing set does.Syntax: p
2 min read