- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 populate a Map using a lambda expression in Java?
A Map is a collection object that maps keys to values in Java. The data can be stored in key/value pairs and each key is unique. These key/value pairs are also called map entries.
In the below example, we can populate a Map using a lambda expression. We have passed Character and Runnable arguments to Map object and pass a lambda expression as the second argument in the put() method of Map class. We need to pass command-line arguments whether the user enters 'h' for Help and 'q' for quit with the help of Scanner class.
Example
import java.util.*; public class PopulateUsingMapLambdaTest { public static void main(String[] args) { Map<Character, Runnable> map = new HashMap<>(); map.put('h', () -> System.out.println("Type h or q")); // lambda expression map.put('q', () -> System.exit(0)); // lambda expression while(true) { System.out.println("Menu"); System.out.println("h) Help"); System.out.println("q) Quit"); char key = new Scanner(System.in).nextLine().charAt(0); if(map.containsKey(key)) map.get(key).run(); } } }
Output
Menu h) Help q) Quit Type h or q : q
- Related Articles
- How to handle an exception using lambda expression in Java?\n
- How to reverse a string using lambda expression in Java?
- How can we iterate the elements of List and Map using lambda expression in Java?
- How to write a conditional expression in lambda expression in Java?
- How to implement IntBinaryOperator using lambda expression in Java?
- How to implement ToIntBiFunction using lambda expression in Java?
- How to implement ToDoubleBiFunction using lambda expression in Java?
- How to implement ToLongFunction using lambda expression in Java?
- How to implement ToLongBiFunction using lambda expression in Java?
- How to implement DoubleToIntFunction using lambda expression in Java?
- How to implement DoubleToLongFunction using lambda expression in Java?
- How to implement DoubleFunction using lambda expression in Java?
- How to implement ToDoubleFunction using lambda expression in Java?
- How to implement DoubleConsumer using lambda expression in Java?
- How to implement PropertyChangeListener using lambda expression in Java?

Advertisements