
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 can we iterate the elements of List and Map using lambda expression in Java?
The lambda expressions are inline code that implements a functional interface without creating an anonymous class. In Java 8, forEach statement can be used along with lambda expression that reduces the looping through a Map to a single statement and also iterates over the elements of a list. The forEach() method defined in an Iterable interface and accepts lambda expression as a parameter.
Example ( List using Lambda Expression)
import java.util.*; public class ListIterateLambdaTest { public static void main(String[] argv) { List<String> countryNames = new ArrayList<String>(); countryNames.add("India"); countryNames.add("England"); countryNames.add("Australia"); countryNames.add("Newzealand"); countryNames.add("South Africa"); // Iterating country names through forEach using Lambda Expression countryNames.forEach(name -> System.out.println(name)); } }
Output
India England Australia Newzealand South Africa
Example (Map using Lambda Expression)
import java.util.*; public class MapIterateLambdaTest { public static void main(String[] args) { Map<String, Integer> ranks = new HashMap<String, Integer>(); ranks.put("India", 1); ranks.put("Australia", 2); ranks.put("England", 3); ranks.put("Newzealand", 4); ranks.put("South Africa", 5); // Iterating through forEach using Lambda Expression ranks.forEach((k,v) -> System.out.println("Team : " + k + ", Rank : " + v)); } }
Output
Team : Newzealand, Rank : 4 Team : England, Rank : 3 Team : South Africa, Rank : 5 Team : Australia, Rank : 2 Team : India, Rank : 1
- Related Questions & Answers
- Java Program to Iterate over ArrayList using Lambda Expression
- How to populate a Map using a lambda expression in Java?
- How can we sort a Map by both key and value using lambda in Java?
- How can we write a multiline lambda expression in Java?
- How can we pass lambda expression in a method in Java?
- How can we write Callable as a lambda expression in Java?
- Program to iterate over a List using Java 8 Lambda
- Can we sort a list with Lambda in Java?
- What kind of variables can we access in a lambda expression in Java?
- How we can iterate through a Python list of tuples?
- Map function and Lambda expression in Python to replace characters
- How to iterate any Map in Java?
- How to implement PropertyChangeListener using lambda expression in Java?
- How to implement DoubleConsumer using lambda expression in Java?
- How to implement IntBinaryOperator using lambda expression in Java?
Advertisements