A lambda expression is one or more line of code which works like function or method. It takes a parameter and returns the value. Lambda expression can be used to convert ArrayList to HashMap.
Syntax:
(parms1, parms2) -> expression
Examples:
Input : List : [1="1", 2="2", 3="3"]
Output: Map : {1=1, 2=2, 3=3, 4=4, 5=5}
Input : List : [1="I", 2="love", 3="Geeks" , 4="for" , 5="Geeks"]
Output: Map : {1=I, 2=Love, 3=Geeks, 4=For, 5=Geeks}
Approach:
- Get the List to be converted into Map
- Create an empty Map
- Put the list values to the map using Lambda Expression
- Return the formed Map
Below is the implementation of the above approach.
Java
import java.util.*;
import java.util.ArrayList;
import java.util.Scanner;
class ListItems {
private Integer key;
private String value;
public ListItems(Integer id, String name)
{
this .key = id;
this .value = name;
}
public Integer getkey() { return key; }
public String getvalue() { return value; }
}
class Main {
public static void main(String[] args)
{
List<ListItems> list = new ArrayList<ListItems>();
list.add( new ListItems( 1 , "I" ));
list.add( new ListItems( 2 , "Love" ));
list.add( new ListItems( 3 , "Geeks" ));
list.add( new ListItems( 4 , "For" ));
list.add( new ListItems( 5 , "Geeks" ));
Map<Integer, String> map = new HashMap<>();
list.forEach(
(n) -> { map.put(n.getkey(), n.getvalue()); });
System.out.println( "Map : " + map);
}
}
|
Output
Map : {1=I, 2=Love, 3=Geeks, 4=For, 5=Geeks}
Time Complexity: O(N), where N is the length of Arraylist.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
17 Aug, 2021
Like Article
Save Article