
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 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
Advertisements