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

raja
raja

e

Updated on: 13-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements