Open In App
Related Articles

Converting ArrayList to HashMap using Method Reference in Java 8

Like Article
Save Article
Report issue

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.


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 program for Converting ArrayList to
// HashMap using method reference in Java 8
import java.util.*;
import java.util.function.Function;
class GFG {
    public static void main(String[] args)
        // creating arraylist to add elements
        ArrayList<String> fruits = new ArrayList<>();
        // 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 =
                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}

Last Updated : 07 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads