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
// Java program for Converting ArrayList to // HashMap using method reference in Java 8 import java.io.*; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; class GFG { public static void main(String[] args) { // creating arraylist to add elements ArrayList<String> fruits = new ArrayList<>(); fruits.add( "Banana" ); fruits.add( "Guava" ); fruits.add( "Pineapple" ); fruits.add( "Apple" ); // printing contents of arraylist before conversion System.out.println( "Elements in ArrayList are : " + fruits); // creating new hashmap and using method reference // with necessary classes for the conversion HashMap<String, Integer> res = fruits.stream().collect(Collectors.toMap( Function.identity(), String::length, (e1, e2) -> e1, HashMap:: new )); // printing the elements of the hashmap System.out.println( "Elements in HashMap are : " + res); } } |
Elements in ArrayList are : [Banana, Guava, Pineapple, Apple] Elements in HashMap are : {Guava=5, Apple=5, Pineapple=9, Banana=6}