Java Program to initialize a HashMap with Lambda Expressions


To initialize a HashMap with Lambda, at first create a HashMpa and use Callable −

HashMap<Integer, Callable<Integer>>map = newHashMap<Integer, Callable<Integer>>()

For key-value pair, you need to initialize them in the following way −

HashMap<Integer, Callable<Integer>>map = newHashMap<Integer, Callable<Integer>>() {
   {
      put(0, () -> {
         return 10;
      });
      put(1, () -> {
         return 20;
      });
   }
};

Example

import java.util.HashMap;
import java.util.concurrent.Callable;
public class Demo {
   public static void main(String[] args) throws Exception {
      HashMap<Integer, Callable<Integer>>map = newHashMap<Integer, Callable<Integer>>() {
         {
            put(0, () -> {
               return 10;
            });
            put(1, () -> {
               return 20;
            });
            put(2, () -> {
               return 30;
            });
            put(3, () -> {
               return 40;
            });
         }};
         System.out.println(map.get(0).call());
         System.out.println(map.get(1).call());
         System.out.println(map.get(2).call());
         System.out.println(map.get(3).call());
      }
   }
}

Output

10
20
30
40

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

797 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements