Converting ArrayList to HashMap using Method Reference in Java 8
Last Updated :
07 Jan, 2021
Data Structures are a boon to everyone who codes. But is there any way to convert a Data Structure into another? Well, it seems that there is! In this article, we will be learning how to convert an ArrayList to HashMap using method reference in Java 8.
Example:
Elements in ArrayList are : [Pen, Pencil, Book, Headphones]
Elements in HashMap are :{Pen=3, Pencil=6, Book=4, Headphones=10}
In Java 8, there are two methods of achieving our goal:
- Converting an ArrayList to HashMap using Lambda expression.
- Converting an ArrayList to HashMap using method reference.
Method: Using Method Reference
Using Method Reference comparatively makes the code look cleaner when compared with Lambda Expression.
Lambda is nothing but code, and if you already have a method that does the same thing, then you can pass the method reference instead of a lambda expression.
- Function.identity() refers to an element making itself as the key of the HashMap.
- String::length allows storing the length of the element as its respected value.
Java
import java.io.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
class GFG {
public static void main(String[] args)
{
ArrayList<String> fruits = new ArrayList<>();
fruits.add( "Banana" );
fruits.add( "Guava" );
fruits.add( "Pineapple" );
fruits.add( "Apple" );
System.out.println( "Elements in ArrayList are : "
+ fruits);
HashMap<String, Integer> res = fruits.stream().collect(Collectors.toMap(
Function.identity(), String::length,
(e1, e2) -> e1, HashMap:: new ));
System.out.println( "Elements in HashMap are : "
+ res);
}
}
|
Output
Elements in ArrayList are : [Banana, Guava, Pineapple, Apple]
Elements in HashMap are : {Guava=5, Apple=5, Pineapple=9, Banana=6}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...