Thursday, August 13, 2015

Java Program to return unique employee list by employee name from added set:


package com.test;

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

public

class Employee {
 private String name;
 private int age;

 public String getName() {
  return name;
 }

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

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 @Override
 public boolean equals(Object arg0) {
  // TODO Auto-generated method stub
  Employee emp = (Employee) arg0;
  return this.name.equals(emp.getName());
 }

 @Override
 public int hashCode() {
  return this.name.hashCode();
 }

 @Override
 public String toString() {
  // TODO Auto-generated method stub
  return this.getName();
 }

 public static void main(String[] args) {
  System.out.println("This is the main method");
  Set set = new HashSet();
  Employee e;
  e = new Employee();
  e.setAge(23);
  e.setName("Ankur");
  set.add(e);
  e = new Employee();
  e.setAge(23);
  e.setName("Surendra");
  set.add(e);
  e = new Employee();
  e.setAge(58);
  e.setName("Surendra");
  set.add(e);
  e = new Employee();
  e.setAge(35);
  e.setName("Surendra");
  set.add(e);
  System.out.println("Returned map is: " + set);
 }
}

Output: This is the main method Returned map is: [Surendra, Ankur]

No comments: