Core Java : Map and HashMap example

Map and HashMap Example: adding employees to map by designation. and getting employees
by designation. I am providing downloading link for this example. If file is deleted from hosting site drop your mail id to get this example

download Map and HashMap example open it with eclipse and run main method to execute



Employee.java

package domain;

public interface Employee {

    public Integer getId();

    public void setId(Integer id);

    public String getFirstName();

    public void setFirstName(String firstName);
    
    public String getLastName();

    public void setLastName(String lastName);
    
    public void setEmail(String email);
    
    public String getEmail();

    public int getPriority();

    public void setPriority(int priority);
    
    public String getDesignation();

    public void setDesignation(String designation);

    public String toDisplayString();

}


EmployeeImpl.java

package domain.impl;

import java.io.Serializable;

import utils.EmployeeIO;
import domain.Employee;

public class EmployeeImpl extends EmployeeIO implements Employee{
    
    private static final long serialVersionUID = 1L;
   
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
    private int priority;
    private String designation;

    @Override
    public Integer getId() {
        return id;
    }
    
    @Override
    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String getFirstName() {
        return firstName;
    }
    
    @Override
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    @Override
    public String getLastName() {
        return lastName;
    }
    
    @Override
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String getEmail() {
        return email;
    }

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

    @Override
    public int getPriority() {
        return priority;
    }

    @Override
    public void setPriority(int priority) {
        this.priority = priority;
    }

    @Override
    public String getDesignation() {
        return designation;
    }

    @Override
    public void setDesignation(String designation) {
        if("CEO".equalsIgnoreCase(designation)){
            setPriority(1);
        }else if("MD".equalsIgnoreCase(designation)){
            setPriority(2);
        }else if("HR".equalsIgnoreCase(designation)){
            setPriority(3);
        }else{
            setPriority(4);
        }
        this.designation = designation;
    }
  
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("EmployeeImpl [id=");
        buffer.append(id);
        buffer.append(", firstName=");
        buffer.append(firstName);
        buffer.append(", lastName=");
        buffer.append(lastName);
        buffer.append(", email=");
        buffer.append(email);
        buffer.append(", priority=");
        buffer.append(priority);
        buffer.append(", designation=");
        buffer.append(designation);
        buffer.append("]");
        return buffer.toString();
    }

    @Override
    public boolean equals(Object object){
        if (object == null) return false;
        if (object == this) return true;
        if (this.getClass() != object.getClass())return false;
        Employee employee = (Employee)object;
        if(this.id.equals(employee.getId())
            && this.firstName.equalsIgnoreCase( employee.getFirstName())
            && this.lastName.equalsIgnoreCase( employee.getLastName())
            && this.email.equalsIgnoreCase( employee.getEmail())
            && this.designation.equalsIgnoreCase(employee.getDesignation()))
            return true;
       return false;
    }

    @Override
    public String toDisplayString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(this.getId());
        buffer.append("\t");
        buffer.append(this.getFirstName());
        buffer.append("\t");
        buffer.append(this.getLastName());
        buffer.append("\t");
        buffer.append(this.getEmail());
        buffer.append("\t");
        buffer.append(this.getDesignation());
        return buffer.toString();
    }    
}


EmployeeService.java

package service;

import java.util.List;

import domain.Employee;

public interface EmployeeService {

    List<Employee> getAll();

    List<Employee> getByDesignation(String designation);

    void addEmployee(Employee employee);

}

EmployeeServiceImpl.java

package service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import service.EmployeeService;

import domain.Employee;

public class EmployeeServiceImpl implements EmployeeService {
 private List<Employee> employees = new ArrayList<Employee>();

 private Map<String, List<Employee>> employeesByDesig 
     = new HashMap<String, List<Employee>>();

 @Override
 public List<Employee> getAll() {
  List<Employee> employees = new ArrayList<Employee>(this.employees);
  return Collections.unmodifiableList(employees);
 }

 @Override
 public List<Employee> getByDesignation(String designation) {
  List<Employee> empsByDesig = employeesByDesig.get(designation);
  if (empsByDesig == null) {
   throw new IllegalArgumentException("Invalid Designation: "
     + designation);
  }
  return empsByDesig;
 }

 @Override
 public void addEmployee(Employee employee) {
  if (employees.contains(employee)) {
   System.out.println("Employee already exists");
  } else {
   this.employees.add(employee);
   saveEmployeesbyDesig(employee);
  }

 }

 private void saveEmployeesbyDesig(Employee employee) {
  String designation = employee.getDesignation();
  List<Employee> employeesList = this.employeesByDesig.get(designation);
  if (employeesList == null) {
   employeesList = new ArrayList<Employee>();
  }
  employeesList.add(employee);
  this.employeesByDesig.put(designation, employeesList);
 }

}


EmployeeIO.java

package utils;

import java.util.List;

import domain.Employee;
import domain.impl.EmployeeImpl;

public class EmployeeIO {

 public static Employee read() {
  Employee employee = new EmployeeImpl();
  employee.setId(KeyBoard.readInt("Enter Id :"));
  employee.setFirstName(KeyBoard.read("Enter First Name :"));
  employee.setLastName(KeyBoard.read("Enter Last Name :"));
  employee.setEmail(KeyBoard.read("Enter Email :"));
  employee.setDesignation(KeyBoard.read("Enter Designation :"));
  return employee;
 }

 public static void out(List<Employee> employees) {
  StringBuilder builder = new StringBuilder();
  builder.append("Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n");
  for (int i = 0; i < employees.size(); i++) {
   builder.append(employees.get(i).toDisplayString());
   builder.append("\n");
  }
  System.out.println(builder);
 }

}

KeyBoard.java
package utils;

import java.util.Scanner;

public class KeyBoard {
  
    public static int readInt(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        try {
            int number = Integer.parseInt(scanner.next());
            return number;
        }
        catch(NumberFormatException e) {
            System.out.println("Invalid Number");
            return readInt(message);
        }            
    }
    
    public static String read(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }    
}

EmployeeMain.java
package utils;

package main;

import service.EmployeeService;
import service.impl.EmployeeServiceImpl;
import utils.EmployeeIO;
import utils.KeyBoard;
import domain.Employee;

public class EmployeeMain {

 public static void main(String[] args) {
  int option = 1;
  EmployeeService empService = new EmployeeServiceImpl();
  do {
   Employee employee = EmployeeIO.read();
   empService.addEmployee(employee);
   option = KeyBoard
     .readInt("Do you want add another employee(1/0) :");

  } while (option == 1);
  System.out.println("Employees list :");
  EmployeeIO.out(empService.getAll());
  String byDesig = KeyBoard.read("Enter Designation : ");
  try {
   EmployeeIO.out(empService.getByDesignation(byDesig));
  } catch (IllegalArgumentException e) {
   System.out.println("Invalid designation : " + byDesig);
  }
 }
}



Output of the programe
Enter Id :1
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :1
Enter Id :1
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Employee already exists
Do you want add another employee(1/0) :1
Enter Id :2
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :admin@myrmidons.co.in
Enter Designation :hr
Do you want add another employee(1/0) :1
Enter Id :3
Enter First Name :kumar
Enter Last Name :jagadeesh
Enter Email :jk.manne@yahoo.com
Enter Designation :programmer
Do you want add another employee(1/0) :1
Enter Id :4
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :admin@myrmidons.co.in
Enter Designation :ceo
Do you want add another employee(1/0) :1
Enter Id :5
Enter First Name :anil
Enter Last Name :kumar
Enter Email :testtest@gmail.com
Enter Designation :hr
Do you want add another employee(1/0) :1
Enter Id :6
Enter First Name :kumar
Enter Last Name :anil
Enter Email :test@gmail.com
Enter Designation :hr
Do you want add another employee(1/0) :0
Employees list :
Id First Name Last Name Email                Designation
1 jagadeesh kumar         mannejkumar@gmail.com developer
2 jagadeesh kumar         admin@myrmidons.co.in hr
3 kumar        jagadeesh jk.manne@yahoo.com programmer
4 jagadeesh kumar         admin@myrmidons.co.in ceo
5 anil         kumar         testtest@gmail.com hr
6 kumar         anil         test@gmail.com         hr

Enter Designation : hr
Id First Name Last Name Email                 Designation
2 jagadeesh kumar         admin@myrmidons.co.in hr
5 anil         kumar         testtest@gmail.com hr
6 kumar         anil         test@gmail.com         hr




Categories: