Open In App

Converting ArrayList to HashMap in Java 8 using a Lambda Expression

Last Updated : 17 Aug, 2021
Comments
Improve
Suggest changes
14 Likes
Like
Report

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:

  1. Get the List to be converted into Map
  2. Create an empty Map
  3. Put the list values to the map using Lambda Expression
  4. Return the formed Map

Below is the implementation of the above approach.


Output
Map : {1=I, 2=Love, 3=Geeks, 4=For, 5=Geeks}

Time Complexity: O(N), where N is the length of Arraylist.


 


Next Article

Similar Reads