Open In App

Converting ArrayList to HashMap using Method Reference in Java 8

Last Updated : 07 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads