Core Java : Set and HashSet example

Set and HashSet Example: adding employees to set and removing duplicates from set. While adding verify the same employee already exists or not by calling contains method and overriding the equals method and hashcode method. contains method calls equals method internally. equals method calls hashcode method.
if name, id, designation, email everthing same then i am treating it as duplicate.

download Set and HashSet example




Employee.java

package com.jagadeesh.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 com.jagadeesh.domain.impl;

import java.io.Serializable;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.utils.EmployeeIO;

public class EmployeeImpl extends EmployeeIO implements Employee {

 private static final long serialVersionUID = 5058287999709032283L;

 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) {
  Employee employee = (Employee) object;
  if (this.hashCode() == employee.hashCode())
   return true;
  return false;
 }
 
  @Override
  public int hashCode(){
        StringBuffer buffer = new StringBuffer();
        buffer.append(this.id);
        buffer.append(this.firstName.hashCode());
        buffer.append(this.lastName.hashCode());
        buffer.append(this.email.hashCode());
        buffer.append(this.designation.hashCode());
        System.out.println(Integer.parseInt(buffer.toString()));
        return Integer.parseInt(buffer.toString()); 
  }

 @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 com.jagadeesh.service;

import java.util.Set;

import com.jagadeesh.domain.Employee;

public interface EmployeeService {

    Set<Employee> getAll();

    void addEmployee(Employee employee);

}

EmployeeServiceImpl.java

package com.jagadeesh.service.impl;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.service.EmployeeService;


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

 @Override
 public Set<Employee> getAll() {
  Set<Employee> employees = new HashSet<Employee>(this.employees);
  return Collections.unmodifiableSet(employees);
 }

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



EmployeeIO.java

package com.jagadeesh.utils;

import java.util.Set;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.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(Set<Employee> employees) {
  StringBuilder builder = new StringBuilder();
  builder.append("Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n");
  for (Employee employee : employees) {
   System.out.println(employee.toDisplayString());
  }
  System.out.println(builder);
  builder.append("\n");
 }

}


KeyBoard.java

package com.jagadeesh.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 com.jagadeesh.main;

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

public class EmployeeMain {
    public static void main(String[] args) throws Exception {
        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("Reading from Set");
        EmployeeIO.out(empService.getAll());
    }
}

Out put of the program

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 :2
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) :testing invalid option
Invalid Number
Do you want add another employee(1/0) :1
Enter Id :3
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :admin@myrmidons.co.in
Enter Designation :developer
Do you want add another employee(1/0) :0
Reading from List
Id First Name Last Name Email  Designation
1 jagadeesh kumar mannejkumar@gmail.com developer
2 jagadeesh kumar mannejkumar@gmail.com developer
3 jagadeesh kumar admin@myrmidons.co.in developer




Categories: