Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to iterate List Using Streams in Java?
In Java, a List is an interface that stores a sequence of elements of similar type. Java provides various ways to iterate over a list, such as using a for loop, forEach loop, iterator object, stream, or forEach() method with a lambda expression.
What is Stream in Java?
In Java, a Stream is an interface, which represents a sequence of elements (or objects) supporting sequential and parallel aggregate operations. These operations can be used to produce the desired result.
The Stream interface provides a method named stream(), which is used to create a sequential stream from the current collection (or List). Following is the syntax of the stream() method:
Collection.stream()
Here, the Collection can be List, ArrayList, etc.
Note: The created sequential stream will have the same sequence of element as List.
Example 1
In the following example, we iterate a list {10, 20, 30, 40} using the Stream. We use the stream() method to create a sequential stream from the current list and use forEach() method with lambda expression (->) to iterate over it:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class iterateList {
public static void main(String[] args) {
//instantiating a list using ArrayList class
List<Integer> list = new ArrayList<>();
//adding element to it
list.add(10);
list.add(20);
list.add(30);
list.add(40);
System.out.println("The list elements are: ");
//creating a sequential stream using the stream() method
Stream<Integer> obj = list.stream();
//iterate over a list using stream
obj.forEach(e -> {
System.out.print(e + " ");
});
}
}
The above program displays the following output:
The list elements are: 10 20 30 40
Example 2
This is another example of iterating a list using a Stream. We create a sequential stream using the stream() method and use forEach() method with lambda expression (->) to iterate over the sequential Stream:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class iterateList {
public static void main(String[] args) {
//instantiating a list using ArrayList class
List<String> languages = new ArrayList<>();
//adding element to it
languages.add("Java");
languages.add("JavaScript");
languages.add("TypeScript");
languages.add("C++");
System.out.println("The list elements are: ");
//creating a sequential stream using stream() method
Stream<String> obj = languages.stream();
//iterate over a list using stream
obj.forEach(lang -> {
System.out.println(lang + " ");
});
}
}
Following is the output of the above program:
The list elements are: Java JavaScript TypeScript C++