How to Store Employee Objects in HashMap

In this example, I show you how to store custom Employee object in HashMap in Java.

How to Store Employee Objects in HashMap

package com.javaguides.collections.hashmapexamples;

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

class Employee {
    private Integer id;
    private String name;
    private String city;

    public Employee(Integer id, String name, String city) {
        this.id = id;
        this.name = name;
        this.city = city;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}

public class HashMapUserDefinedObjectExample {
    public static void main(String[] args) {

        Map<Integer, Employee> employeesMap = new HashMap<>();
        employeesMap.put(1001, new Employee(1001, "Ramesh", "Bengaluru"));
        employeesMap.put(1002, new Employee(1002, "John", "New York"));
        employeesMap.put(1003, new Employee(1003, "Jack", "Paris"));

        System.out.println(employeesMap);
    }
}

Output

{1001=Employee{name='Ramesh', city='Bengaluru'}, 
1002=Employee{name='John', city='New York'}, 
1003=Employee{name='Jack', city='Paris'}}

Comments