
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
Iterate Over ArrayList Using Lambda Expression in Java
The ArrayList class is a resizable array that can be found in java.util package. The difference between a built-in array and an ArrayList in Java is that the size of an array cannot be modified.
Lambda Expression is a feature that was introduced in Java 8. It is useful when we use collections, such as ArrayList, Set, or Map, and we want to perform operations on the elements of these collections.
In this article, we will learn how to iterate over an ArrayList using a lambda expression in Java.
Iterating Over an ArrayList Using Lambda Expressions
There are two main ways to iterate over an ArrayList using a lambda expression:
Using forEach() Method with Lambda Expression
We use the forEach() method of the Iterable interface to iterate over an ArrayList using a lambda expression. The forEach() method takes a lambda expression as an argument, which is applied to each element of the ArrayList.
Syntax
Following is the syntax to iterate over an ArrayList using a lambda expression:
list.forEach(element -> { // perform operation on element });
Example
In the below example, we will create an ArrayList of integers and then use the forEach() method with a lambda expression to print each element of the ArrayList.
import java.util.ArrayList; import java.util.List; public class IterateUsingLambda { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.forEach(element -> System.out.println("Element: " + element)); } }
Output
Following is the output of the above code:
Element: 1 Element: 2 Element: 3 Element: 4
Using Method Reference
In addition to using a lambda expression, we can also use a method reference to iterate over an ArrayList. A method reference is a shorthand notation of a lambda expression to call a method.
Syntax
list.forEach(System.out::println);
Example
In the example below, we will use a method reference to print each element of the ArrayList.
import java.util.ArrayList; import java.util.List; public class IterateUsingMethodReference { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.forEach(System.out::println); } }
Output
Following is the output of the above code:
1 2 3 4