Java Collection How to - Initialize HashMap with lambda expressions








Question

We would like to know how to initialize HashMap with lambda expressions.

Answer

import java.util.HashMap;
import java.util.concurrent.Callable;
//from w  w  w  .ja  v  a 2  s  . c  o  m
public class Main {

  public static void main(String[] args) throws Exception {

    HashMap<Integer, Callable<String>> m = new HashMap<Integer, Callable<String>>() {
      {
        put(0, () -> {
          return "n";
        });
        put(1, () -> {
          return "m";
        });
      }
    };
    System.out.println(m.get(0).call());
  }

}

The code above generates the following result.