Skip to content
Related Articles

Related Articles

Improve Article

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:

  1. Converting an ArrayList to HashMap using Lambda expression.
  2. 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);
    }
}
Output
Elements in ArrayList are : [Banana, Guava, Pineapple, Apple]
Elements in HashMap are : {Guava=5, Apple=5, Pineapple=9, Banana=6}

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :