How to populate a Map using a lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

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
Published on 06-Jan-2020 17:35:37
Advertisements