Java code for store object in map and get by object value

To store objects in a Map and retrieve them using an object value in Java, you can use the Map interface along with appropriate key-value pairs. 

Here's an example:

import java.util.HashMap;
import java.util.Map;

class Person {
    private String name;

    public Person(String name) { = name;

    public String getName() {
        return name;

public class ObjectMapExample {
    public static void main(String[] args) {
        // Create a Map to store Person objects
        Map<String, Person> personMap = new HashMap<>();

        // Create Person objects
        Person person1 = new Person("Alice");
        Person person2 = new Person("Bob");

        // Add Person objects to the map
        personMap.put(person1.getName(), person1);
        personMap.put(person2.getName(), person2);

        // Retrieve Person object using object value
        String nameToSearch = "Bob";
        Person retrievedPerson = personMap.get(nameToSearch);

        if (retrievedPerson != null) {
            System.out.println("Person found: " + retrievedPerson.getName());
        } else {
            System.out.println("Person not found!");

In the above code, we create a Person class with a name attribute and a corresponding getter method. Then, we create a Map called personMap with String keys and Person values.

We create two Person objects, person1 and person2, and add them to the personMap using their names as keys. In this example, we use the getName() method of Person as the key for simplicity, but you can choose any unique identifier as the key.

To retrieve a Person object from the personMap using the object value, we provide the desired name to search (nameToSearch) and use the get() method of the Map with the key value. If the key is found, the corresponding Person object is retrieved, and we can perform further operations on it.

In the example, we search for the name "Bob" and print the name of the retrieved Person object if found.

Note that if the key value is not found in the Map, the get() method returns null. Therefore, it's essential to handle the case where the desired object is not found in the Map.