- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Initialize HashMap in Java
- Java Program to create a new list with values from existing list with Lambda Expressions
- Java Program to get the reverse of an Integer array with Lambda Expressions
- How to debug lambda expressions in Java?
- What are lambda expressions in Java?
- Are lambda expressions objects in Java?
- How to initialize an array using lambda expression in Java?
- Java Program to Initialize a List
- What are block lambda expressions in Java?
- Why we use lambda expressions in Java?
- How can we use lambda expressions with functional interfaces in Java?
- How to create a thread using lambda expressions in Java?\n
- Java Program to Iterate over a HashMap
- Differences between Lambda Expressions and Closures in Java?
- How to implement the listeners using lambda expressions in Java?

Advertisements