How to Convert Object to Map in Java

Tags: MapUtils Object Map

In this Java tutorial, we learn how to implement a Java utility class to convert an object to a Map object in Java programming language.

How to convert object to HashMap in Java

At this first step, create a new Java class named MapUtils, implement a static method named toMap(Object value) with the following steps to convert object to Map:

  • Create a new HashMap object as a result of method.
  • Use the Object.getClass().getDeclaredFields() method to get the Field[] array.
  • Loop through the Field[] array, each item use Field.getName() and Field.get(Object obj) method to get the field name and value to put to the result HashMap

MapUtils.java

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class MapUtils {

    /**
     * This method to convert an object to a Map
     * @param value the Object to convert
     * @return the Map result
     */
    public static Map toMap(Object value) {
        Map<Object, Object> result = new HashMap<>();
        Field[] fields = value.getClass().getDeclaredFields();
        for(Field field : fields) {
            try {
                field.setAccessible(true);
                result.put(field.getName(), field.get(value));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return result;
    }
}

For example, we have a Java class named Contact as below.

Contact.java

public class Contact {
    private String firstName;
    private String lastName;
    private String email;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

In the following example Java code, we learn how to convert a Contact object to a HashMap in Java program.

MapUtilsExample.java

import java.util.Map;

public class MapUtilsExample {
    public static void main(String... args) {
        Contact contact = new Contact();
        contact.setFirstName("Simple");
        contact.setLastName("Solution");
        contact.setEmail("contact@simplesolution.dev");

        // Convert Object to Map
        Map map = MapUtils.toMap(contact);

        System.out.println(map);
    }
}
The output as below.
{firstName=Simple, lastName=Solution, email=contact@simplesolution.dev}

Happy Coding 😊

Java Convert Hex String to Byte Array

Java Convert Byte Array to Hex String

Java Check a Valid TCP Port Number

Java How to Concatenate two Arrays