
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
Populate a Map Using 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
Advertisements