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
// Converting ArrayList to HashMap // in Java 8 using a Lambda Expression import java.util.*; import java.util.ArrayList; import java.util.Scanner; // here we are making a class , and we will make class ListItems { // key will act as an id of the value private Integer key; // value will be the value of the above key private String value; // create constructor for reference public ListItems(Integer id, String name) { // assigning the value of key and value this .key = id; this .value = name; } // return private variable key public Integer getkey() { return key; } // return private variable name public String getvalue() { return value; } } class Main { public static void main(String[] args) { // Write your code here // Creating a List of type ListItems using ArrayList List<ListItems> list = new ArrayList<ListItems>(); // add the member of list 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 which will store the list items Map<Integer, String> map = new HashMap<>(); // for (ListItems n : list) { map.put(n.getkey(), // n.getvalue()); } // the below lambda performs the same task as the // above given for loop will do // put the list items in the Map list.forEach( (n) -> { map.put(n.getkey(), n.getvalue()); }); // Printing the given map System.out.println( "Map : " + map); } } |
Map : {1=I, 2=Love, 3=Geeks, 4=For, 5=Geeks}
Time Complexity: O(N), where N is the length of Arraylist.