How to get name from a list of employees - java

I am trying to print "name" of an employee from a list of employees. Below is my pojo class.
import java.time.LocalDate;
public class Employee {
private String name;
private String empID;
private Designation designation;
private LocalDate dateOfJoining;
private int monthlySalary;
public Employee(String name, String empID, Designation designation, LocalDate dateOfJoining, int monthlySalary) {
super();
this.name = name;
this.empID = empID;
this.designation = designation;
this.dateOfJoining = dateOfJoining;
this.monthlySalary = monthlySalary;
}
public Employee() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmpID() {
return empID;
}
public void setEmpID(String empID) {
this.empID = empID;
}
public Designation getDesignation() {
return designation;
}
public void setDesignation(Designation designation) {
this.designation = designation;
}
public LocalDate getDOJ() {
return dateOfJoining;
}
public void setDOJ(LocalDate dOJ) {
dateOfJoining = dOJ;
}
public int getMonthlySalary() {
return monthlySalary;
}
public void setMonthlySalary(int monthlySalary) {
this.monthlySalary = monthlySalary;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dateOfJoining == null) ? 0 : dateOfJoining.hashCode());
result = prime * result + ((designation == null) ? 0 : designation.hashCode());
result = prime * result + ((empID == null) ? 0 : empID.hashCode());
result = prime * result + monthlySalary;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (dateOfJoining == null) {
if (other.dateOfJoining != null)
return false;
} else if (!dateOfJoining.equals(other.dateOfJoining))
return false;
if (designation == null) {
if (other.designation != null)
return false;
} else if (!designation.equals(other.designation))
return false;
if (empID == null) {
if (other.empID != null)
return false;
} else if (!empID.equals(other.empID))
return false;
if (monthlySalary != other.monthlySalary)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
#Override
public String toString() {
return "Employee [name=" + name + ", empID=" + empID + ", designation=" + designation + ", DOJ=" + dateOfJoining
+ ", monthlySalary=" + monthlySalary + "]";
}
}
Now while I am trying to print the "name", I am getting null value.
Please see as below,
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Employecomparable {
public static void main(String[] args) {
JoiningDate jd = new JoiningDate();
Employee emp = new Employee();
List<Employee> listofemployee = new ArrayList<>();
listofemployee.add(new Employee("abc", "12345", Designation.ASE,jd.date1 , 20000));
listofemployee.add(new Employee("abcd", "24680", Designation.SE, jd.date2, 30000));
listofemployee.add(new Employee("abcde", "13570", Designation.SSE,jd.date3, 40000));
listofemployee.add(new Employee("abcdef", "13690", Designation.TL, jd.date4, 60000));
listofemployee.add(new Employee("xyz", "10909", Designation.AM, jd.date5, 800000));
listofemployee.add(new Employee("koool", "89076", Designation.M, jd.date6, 2000));
System.out.println("The name of employee is "+emp.getName());
I am getting the output as "null".
In console I get, The name of employee is null.
How do i print the name?
Please help!

To print the name of a particular employee, kindly update the emp object.
emp = listofemployee.get(indexWithinTheList);
System.out.println("The name of employee is "+emp.getName());
Example:
emp = listofemployee.get(0);
System.out.println("The name of employee is "+emp.getName());
Output : The name of employee is abc

You may want to iterate over your employee and then print the name. Reason you get null is you created Employee object with default constructor. Which would mean name being string object would take default null value which is what you see.
If you want to print employee names, you could do the following:
for (Employee employee: listofemployee) {
System.out.println("The name of employee is " + employee.getName());
}
Since you are using List interface, you can access individual object by it's index. E.g. to get first employee name:
System.out.println("The name of employee is " + listofemployee.get(0).getName());

The error you are getting is because you have created the Employee object like below.
Employee emp = new Employee(); After that you are populating the list using new Employee. But you have not set any value to variable emp.so getName from emp will return null. If you want to get the value from emp. You first need to set the name using emp.SetName("Any name"); No you will get the value using emp.getName();

1 - Create Employee object like below:-
Employee emp =new Employee("xyz", "10909", Designation.AM, jd.date5,
800000);
2 - Then store into list.
3 - After that iterate over list and print result as per your requirement.
public static void main(String[] args) {
JoiningDate jd = new JoiningDate();
Employee emp = new Employee();
List<Employee> listofemployee = new ArrayList<>();
emp = new Employee("abc", "12345", Designation.ASE,jd.date1 , 20000);
listofemployee.add(emp);
emp =new Employee("abcd", "24680", Designation.SE, jd.date2, 30000);
listofemployee.add(emp);
emp =new Employee("abcde", "13570", Designation.SSE,jd.date3, 40000);
listofemployee.add(emp);
emp = new Employee("abcdef", "13690", Designation.TL, jd.date4, 60000);
listofemployee.add(emp);
emp =new Employee("koool", "89076", Designation.M, jd.date6, 2000);
listofemployee.add(emp);
emp =new Employee("xyz", "10909", Designation.AM, jd.date5, 800000);
listofemployee.add(emp);
System.out.println("The name of employee is "+emp.getName());
Iterator<Employee> itr = listofemployee.iterator();
// checking the next element availabilty
while (itr.hasNext())
{
System.out.println("name " + (itr.next()).getName());
}
}

Related

how to add two objects?

I have two classes:-
public class Employee {
private String name;
private String DOB;
private String techicalSkill;
Employee(){
}
Employee(String name, String DOB, String techicalSkill){
this.name=name;
this.DOB=DOB;
this.techicalSkill=techicalSkill;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
DOB = dOB;
}
public String getTechicalSkill() {
return techicalSkill;
}
public void setTechicalSkill(String techicalSkill) {
this.techicalSkill = techicalSkill;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((DOB == null) ? 0 : DOB.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((techicalSkill == null) ? 0 : techicalSkill.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (DOB == null) {
if (other.DOB != null)
return false;
} else if (!DOB.equals(other.DOB))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (techicalSkill == null) {
if (other.techicalSkill != null)
return false;
} else if (!techicalSkill.equals(other.techicalSkill))
return false;
return true;
}
#Override
public String toString() {
return "Employee [name=" + name + ", DOB=" + DOB + ", techicalSkill=" + techicalSkill + "]";
}
}
and
package learning;
public class Person {
private String address;
private int age;
private int weight;
Person(){
}
public Person(String address, int age, int weight) {
super();
this.address = address;
this.age = age;
this.weight = weight;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + age;
result = prime * result + weight;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (age != other.age)
return false;
if (weight != other.weight)
return false;
return true;
}
#Override
public String toString() {
return "Person [address=" + address + ", age=" + age + ", weight=" + weight + "]";
}
}
Now i have created a main class inside which the details are present:-
import java.util.ArrayList;
public class Main {
Employee e1 = new Employee();
Person p1 = new Person();
public static void main(String[] args) {
ArrayList<Employee> arraylist = new ArrayList<>();
arraylist.add(new Employee("Somduti", "31-08-1992", "Java"));
arraylist.add(new Employee("abc", "30-01-1995", "Android"));
arraylist.add(new Employee("xyz", "24-12-1988", "DotNet"));
arraylist.add(new Employee("Sanj", "01-10-1986", "IOS"));
arraylist.add(new Employee("Pink", "19-07-1991", "ETL"));
System.out.println(arraylist);
ArrayList<Person> arraylist1 = new ArrayList<>();
arraylist1.add(new Person("India", 27, 57));
arraylist1.add(new Person("US", 22, 64));
arraylist1.add(new Person("Australia", 31, 69));
arraylist1.add(new Person("France", 33, 77));
arraylist1.add(new Person("Germany", 28, 55));
System.out.println(arraylist1);
}
}
I want to add the two Objects and print the result as below:-
name=Somduti, DOB=31-08-1992, techicalSkill=Java address=India, age=27, weight=57
How do I that?
I think what you want to achieve is a relation between employees and persons. There are various ways to do that. Here are two common solutions:
Association: Add a person-field to the employee class. This looks like: "private Person person;" within the employee class.
Inheritance: An employee is a specific type of person, so you can let employee "extend" the person class. This looks like: public class Employee extends Person ...
Both ways have advantages and disadvantages. For example: Inheritance is a strong relationship, that you might want in this case. Association is a weaker type of relation, so that you could "replace" the person information of an employee (which might not be want you want).
Add the below additional field in the Employee class as follows:
public class Employee {
private String name;
private String DOB;
private String techicalSkill;
private Person person; // Additional field
Employee() {
}
/**
* #param name
* #param dOB
* #param techicalSkill
* #param person
*/
public Employee(final String name, final String dOB, final String techicalSkill, final Person person) {
super();
this.name = name;
this.DOB = dOB;
this.techicalSkill = techicalSkill;
this.person = person; //additional argument in Constructor
}
}
P.S: No changes to the Person class
Test Main:
Person person = new Person("India", 27, 57);
Employee employee = new Employee("Somduti", "31-08-1992", "Java", person);
System.out.println("name= " + employee.getName() + ", DOB= " + employee.getDOB() + ",techicalSkill= " +
employee.getTechicalSkill() + " address= " + employee.getPerson().getAddress() + ", age= " +
employee.getPerson().getAge() + " weight= " + employee.getPerson().getWeight());
Output:
name= Somduti, DOB= 31-08-1992,techicalSkill= Java address= India, age= 27 weight= 57

TreeSet sorts correctly for int but fails for a String?

I want to create a 2 TreeSets to hold sorted Employee Objects,one based on Employee id(int) and other based on Employee name(String).
I have overridden equals() and hashcode() and toString() in the Employee class shown below.
public class Employee {
private int id;
private String name;
#Override
public String toString() {
return "\nEmployee [id=" + id + ", name=" + name + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public Employee(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
I made 2 Comparators for the 2 TreeSets,
public class EmployeeNameComparator implements Comparator<Employee> {
#Override
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
public class EmployeeIdComparator implements Comparator<Employee>{
#Override
public int compare(Employee o1, Employee o2) {
if(o1.getId()<o2.getId())return -1;
else if(o1.getId()>o2.getId())return 1;
else return 0;
}
}
The Problem is the TreeSet which stores elements based on Id prints the output correctly ,but the one which stores the elements based on name does not print it as expected,
public class TreeSetTest {
public static void main(String[] args) {
//Employee Objects
Employee e1=new Employee(24, " bJohn");
Employee e2=new Employee(14, "aJonathan");
Employee e3=new Employee(4, "cJobs");
//put into a List and Print as it is
ArrayList<Employee> employees=new ArrayList<Employee>(3);
employees.add(e1);employees.add(e2);employees.add(e3);
System.out.println(employees);
//now create 2 Treesets with sorted id and Sorted Name
//the 2 comparators for name and Id
EmployeeNameComparator employeeNameComparator=new EmployeeNameComparator();
EmployeeIdComparator employeeIdComparator=new EmployeeIdComparator();
//creating the 2 tree Sets
TreeSet<Employee> employeeNameTree=new TreeSet<Employee>(employeeNameComparator);
employeeNameTree.addAll(employees);
TreeSet<Employee> employeesIdTree=new TreeSet<Employee>(employeeIdComparator);
employeesIdTree.addAll(employees);
//Printing both
System.out.println(employeeNameTree);
System.out.println(employeesIdTree);
}
}
Output:
[Employee [id=24, name= bJohn], Employee [id=14, name=aJonathan], Employee [id=4, name=cJobs]]
[Employee [id=24, name= bJohn], Employee [id=14, name=aJonathan], Employee [id=4, name=cJobs]]
[Employee [id=4, name=cJobs], Employee [id=14, name=aJonathan], Employee [id=24, name= bJohn]]
As you can see ,row 2 isn't sorted based on the name values.
My assumption all along is that the a.compareTo(b) in String class checks if String 'a' comes before or after String 'b' in the dictionary ie checks the alphabetical order , am i right ?, then why isn't the output as expected?

Organizing array list of objects JAVA

I'm having troubling organizing my list of employees. I just need to organize them according to their employee type (first two letters). Each object starts with the employee code which are the first two letters. This is what I need to separate the position types but for some reason I can't grab them.
Here is the file that I am creating the objects out of and storing them in the arrays.
PW_1234,James,Bond,01/02/10,1,10 PW_1235,John,Brown,02/03/10,2,10.5
PW_1236,Howard,Johnson,03/04/10,3,11
PW_1237,Francis,Themule,04/05/11,4,10.75
PW_1238,Mathew,Lewis,05/06/11,1,12.75
PW_1239,Mark,Bixton,05/13/11,2,13
PW_1242,Sarah,Glover,05/14/11,1,13.75 PW_1245,John,Doe,05/15/11,4,10.5
PW_1245,Mary,Doe,05/15/11,4,10.5
TL_1248,Abel,English,05/16/11,3,16.5,0.01,100,89
TL_1251,Eustis,Clauser,05/17/11,2,16,0.02,100,9
SU_1254,Henry,Hollowman,05/18/11,1,40000,0.01
PW_1240,Luke,Sailor,01/22/12,3,14.5 PW_1243,Jane,Baker,01/23/12,2,14
PW_1243,Jane,Baker,01/23/12,2,14
TL_1246,David,Brief,01/24/12,1,14.75,0.01,100,57
PW_1246,David,Doson,01/24/12,1,14.75
TL_1249,Baker,Anderson,01/25/12,4,11.5,0.01,100,100
TL_1252,Frank,Donson,01/26/12,3,17.5,0.02,100,39
SU_1255,Issac,Asimov,01/27/12,2,43000,0.02
SU_1256,Issac,Shoreman,01/28/12,3,39000,0.01
SU_1257,Issac,Roberts,01/29/12,4,35500,0.01
PW_1241,John,Candy,11/23/13,4,9.5 PW_1244,Kate,Smith,11/24/13,3,15.5
PW_1244,Kate,Handle,11/24/13,3,15.5
TL_1247,Samual,Dempky,11/25/13,2,15,0.01,100,10
TL_1250,Charley,Boman,11/26/13,1,15.75,0.01,100,50
TL_1253,George,Fritzmen,11/27/13,4,12.5,0.02,100,27
Here is the code:
private String makeEmployeeList()
{
String list = "";
for(int i=0; i < employees.length; i++)
{
list += "\n"+employees[i].toString();
if(employees[i]substring(0,2).equals("SU"))
{
list += "\n"+employees[i].toString();
}
}
return list;
}
**Here is how the employees array is created:
private Employee[] employees;
**Here is how everything is loaded into it.
public void loadEmployeesFromFile(String fileName)
{
File inFile = new File(fileName);
if(inFile.exists()) // MAKE SURE FILE EXISTS
{
try
{
BufferedReader inReader = new BufferedReader(new FileReader(inFile));
inReader.mark(32000);
String inLine = inReader.readLine();
//************************************
// Counting rows to set array size
//************************************
int rowCount = 0;
while (inLine != null && !inLine.equals(""))
{
rowCount++;
inLine = inReader.readLine();
}
inReader.reset();
//*******************
// re-reading data
//*******************
this.employees = new Employee[rowCount];
for(int rowIndex = 0;rowIndex < rowCount; rowIndex++)
{
inLine = inReader.readLine();
Scanner employeeScanner = new Scanner(inLine).useDelimiter(",");
String workerType = employeeScanner.next();
String firstName = employeeScanner.next();
String lastName = employeeScanner.next();
String hireDate = employeeScanner.next();
int shift = employeeScanner.nextInt();
if(workerType.substring(0,2).equals("PW"))
{
double pay = employeeScanner.nextDouble();
employees[rowIndex]= new ProductionWorker(workerType, firstName, lastName, hireDate, shift, pay);
}
else if(workerType.substring(0,2).equals("TL"))
{
double pay = employeeScanner.nextDouble();
double bonusRate = employeeScanner.nextDouble();
int reqHours = employeeScanner.nextInt();
int recHours = employeeScanner.nextInt();
employees[rowIndex]= new TeamLeader(workerType, firstName, lastName, hireDate, shift, pay, bonusRate, reqHours, recHours);
}
else if(workerType.substring(0,2).equals("SU"))
{
double salary = employeeScanner.nextDouble();
double bonusRate = employeeScanner.nextDouble();
employees[rowIndex]= new ShiftSupervisor(workerType, firstName, lastName, hireDate, shift, salary, bonusRate );
}
}
return;
}catch(IOException ioe)
{
System.err.print("\nTrouble reading employee file: "+fileName);
}
}
JOptionPane.showMessageDialog(null, "\nFile Name does not exist!\n Process terminating!");
System.exit(0);
}
private String makeEmployeeList(){
StringBuilder sbSU = null;
for(int i=0; i < employees.length; i++)
{
sbSU = new StringBuilder();
if(employees[i].substring(0,2).equals("SU"))
{
sbSU.append(employees[i].toString());
}
}
return sbSU.toString();
}
First of all, you missed a dot after emplyees[i] subsrting
As string is an immutable object, I suggest you use StringBuilder and its append method instead of +=. and use its toString() method to convert StringBuilder to a String. You also need to override your Employees's toString method.
to sort the employees in an array, you need to implements Comparable or Comparator interface so that the Array knows which criteria to use when sorting your employees, in your case it is to compare the employee's type
As you are using JOptionPane you can use html inside to give it format. Make an Employee class and make it's natural order by type, or you can use a Comparator if you don't want to use Comparable
I made a complete example for you.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JOptionPane;
public class Employee implements Comparable<Employee> {
private String type;
private String name;
public Employee(String type, String name) {
super();
this.type = type;
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
public int compareTo(Employee o) {
if (this.type.equals(o.type)) {
return name.compareTo(o.name);
}
return type.compareTo(o.type);
}
public static void main(String[] args) {
List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee("CA","John"));
employees.add(new Employee("CA", "Suzy"));
employees.add(new Employee("TA","Malcom"));
employees.add(new Employee("AA","Rose"));
// Sort the list by type as its natural order or use proper Comparator
Collections.sort(employees);
StringBuilder sb = new StringBuilder();
sb.append("<html><table><tr><td>Type</td><td>Name</td></tr>");
for (Employee e : employees) {
sb.append("<tr>");
sb.append("<td> ").append(e.getType()).append("</td>");
sb.append("<td> ").append(e.getName()).append("</td>");
sb.append("</tr>");
}
sb.append("</table></html>");
JOptionPane.showMessageDialog(null, sb);
}
}
Output:

Compare elements in list and remove if some properties are the same

I have an array list of objects which contains eg:
Name
Address
Phone
Many other properties...
I wish to remove some objects in this list, if some of the properties has the same value as other objects in the array list. I need to loop though the whole list and see if the Name, Address and Phone already exists in this list. I can not do a simple:
for (...)
if (!newlist.contains(element)) { newlist.add(element); }
As I only need to check specific properties are the same before adding the element to a new list.
Can anyone guide me in the right direction?
How about using Set with a custom Comparator ? Have your object class implement Comparable. In the compare method you can then write your test to match the objects exactly how you need it.
Create a Key Class let us say Employee.java with below code.
package com.innovation;
public class Employee {
private String name;
private String address;
private String phone;
public Employee() {
super();
}
public Employee(String name, String address, String phone) {
super();
this.name = name;
this.address = address;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((phone == null) ? 0 : phone.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (phone == null) {
if (other.phone != null)
return false;
} else if (!phone.equals(other.phone))
return false;
return true;
}
#Override
public String toString() {
return "Employee [name=" + name + ", address=" + address + ", phone="
+ phone + "]";
}
}
Now create a Client class where you want to apply your logic let us assume a class containing main method say Client.java
package com.innovation;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Client {
public static void main(String[] args) {
Set<Employee> empSet = new HashSet<Employee>(populateList());
for (Employee employee : empSet)
{
System.out.println(employee);
}
}
public static List<Employee> populateList()
{
List<Employee> lsts = new ArrayList<Employee>();
lsts.add(new Employee("rais","gurgaon","123456"));
lsts.add(new Employee("alam","Delhi","123685"));
lsts.add(new Employee("shyam","Mumbai","1257456"));
lsts.add(new Employee("ramesh","Ahmadabad","196356"));
lsts.add(new Employee("rais","gurgaon","123456"));
lsts.add(new Employee("rais","gurgaon","123456"));
lsts.add(new Employee("rais","gurgaon","123456"));
return lsts;
}
}
You will see below out put. it is clearly visible that duplicate entry present in list is removed in set. it all magic of good implementation of equals and hashcode method.
Employee [name=rais, address=gurgaon, phone=123456]
Employee [name=ramesh, address=Ahmadabad, phone=196356]
Employee [name=alam, address=Delhi, phone=123685]
Employee [name=shyam, address=Mumbai, phone=1257456]

remove duplicate object in Java

I've User object a shown below:
User.java:
public class User {
public String firstName;
public String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public int hashCode() {
return (this.firstName.hashCode() + this.lastName.hashCode());
}
#Override
public boolean equals(Object obj) {
if(obj instanceof User) {
User temp = (User) obj;
if(this.firstName.equals(temp.firstName) && this.lastName.equals(temp.lastName)) {
return true;
}
}
return false;
}
}
And main program is shown below:
import java.util.*;
class pp {
public static void main(String[] args) {
List<User[]> a = new ArrayList<User[]>();
User[] u = new User[3];
u[0] = new User();
u[0].setFirstName("Mike"); u[0].setLastName("Jordon");
u[1] = new User();
u[1].setFirstName("Jack"); u[1].setLastName("Nicolson");
u[2] = new User();
u[2].setFirstName("Jack"); u[2].setLastName("Nicolson");
a.add(u);
Set<User[]> s = new HashSet<User[]>(a);
for (User[] ss : s) {
for (int i=0; i<ss.length; i++) {
System.out.println(ss[i].getFirstName() + " " + ss[i].getLastName());
}
}
}
}
I'm expecting output to be
Mike Jordon
Jack Nicolson
But somehow, its retaining duplicate object & printing as:
Mike Jordon
Jack Nicolson
Jack Nicolson
Can any one tell me what I'm missing??
Thanks!
Your equals method should be like :
#Override
public boolean equals(Object obj) {
if(obj instanceof User) {
User temp = (User) obj;
if(this.firstName.equals(temp.firstName) && this.lastName.equals(temp.lastName)) {
return true;
}
}
return false;
}
I have gone through your questions and understood the requirement. Please find the similar kind of code I have implemented and also successfully removed objects from a collection those having duplicate values.
#Snipet...
Employee.java
==============
package com.hcl;
public class Employee {
public String empid;
public String empname;
public double sal;
public int age;
public Employee(){
}
public Employee(String empid,String empname,double sal,int age){
this.empid = empid;
this.empname = empname;
this.sal = sal;
this.age = age;
}
public String getEmpid() {
return empid;
}
public void setEmpid(String empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/**
* This override method playes a major role to remove duplicate values
*/
#Override
public int hashCode() {
return (this.empid.hashCode() + this.empname.hashCode()+String.valueOf(this.sal).hashCode()+String.valueOf(this.age).hashCode());
}
/**
* This override method plays a major role to remove duplicate values
*/
#Override
public boolean equals(Object obj) {
if(obj instanceof Employee) {
Employee temp = (Employee) obj;
if(this.empid.equals(temp.empid) && this.empname.equals(temp.empname) && String.valueOf(this.sal).equals(String.valueOf(temp.sal)) && String.valueOf(this.age).equals(String.valueOf(temp.age))) {
return true;
}
}
return false;
}
}
#Snipet..........
RemoveDuplicateObjects.java
=============================
package com.hcl;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RemoveDuplicateObjects {
public static void main(String[] args) {
Employee emp1 = new Employee("1","bapi",1000,31);
Employee emp2 = new Employee("2","mano",2000,29);
Employee emp3 = new Employee("1","bapi",1000,31); // emp3 == emp1 duplicate object
Employee emp4 = new Employee("3","Rohan",3000,27);
Employee emp5 = new Employee("1","bapi",1000,31); // emp5 == emp3 == emp1 duplicate object
RemoveDuplicateObjects obj = new RemoveDuplicateObjects();
// empList contains objects having duplicate values. How to remove duplicate?
List<Employee> empList = new ArrayList<Employee>();
empList.add(emp1);
empList.add(emp2);
empList.add(emp3);
empList.add(emp4);
empList.add(emp5);
if(emp1.equals(emp2)){
System.out.println("emp1 and emp2 are equal");
}
if(emp1.equals(emp3)){
System.out.println("emp1 and emp3 are equal");
}
obj.removeDuplicate(empList);
}
// method is used for removing objects having duplicate values
private void removeDuplicate(List<Employee> empList) {
Set<Employee> empSet = new HashSet<Employee>();
empSet.addAll(empList);
for(Employee e: empSet){
System.out.println("id = "+e.getEmpid());
System.out.println("name = "+e.getEmpname());
System.out.println("sal = "+e.getSal());
System.out.println("age = "+e.getAge());
}
}
}
Done! Now you can run the program and analyze the solution.
I suppose you want this:
class pp {
public static void main(String[] args) {
Set<User> a = new HashSet<User>();
User u = new User();
u.setFirstName("Mike"); u.setLastName("Jordon");
a.add(u);
u = new User();
u.setFirstName("Jack"); u.setLastName("Nicolson");
a.add(u);
u = new User();
u.setFirstName("Jack"); u.setLastName("Nicolson");
a.add(u);
for (User ss : a) {
System.out.println(ss.getFirstName() + " " + ss.getLastName());
}
}
}
try this my friend :
Iterator i = a.iterator();
while (i.hasNext()) {
User u = (User) i.next();
boolean match = false;
Iterator j = a.iterator();
boolean once = true;
while (j.hasNext()) {
if(once){j.next();} // to skip own occurence only once
once = false;
User u2 = (User) j.next();
if (u.getFirstName().equals(u2.getFirstName())
&& u.getLastName().equals(u2.getLastName())) {
match = true;
}
}
if (!match) {
// print
}
}
Override the equals method as suggested by Jason.
Now for removing duplicates you need to use Set.
List allows duplicate values so you will always have duplicate values. Set doesnot allow duplicate value so it will solve your problem.
You're using a Set of arrays, where the set has one element, namely an array of three Users. Arrays don't enforce or check uniqueness, which is why you get the same User twice. If you removed the arrays altogether, and simply used a Set, you'd get the "unique" behaviour you want.
First you should use a Set to store objects instead of a array if you dont want duplicates. (Arrays and List do allow duplicate objects to be stores)
Second your equals methods should use String.equal method for comparison and should check for null values too to be on the safe side. I would use the IDE's auto generate feature for hashcode and equals methods always (i.e. Eclipse Source -> Generate hashCode() and equals()...)
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
and main method
public static void main(String[] args) {
List<Set<User>> a = new ArrayList<Set<User>>();
Set<User> set = new HashSet<User>();
User u = new User();
u.setFirstName("Mike"); u.setLastName("Jordon");
set.add(u);
u = new User();
u.setFirstName("Jack"); u.setLastName("Nicolson");
set.add(u);
u = new User();
u.setFirstName("Jack"); u.setLastName("Nicolson");
set.add(u);
a.add(set);
for (Set<User> ss : a) {
for (User user : ss) {
System.out.println(user.getFirstName() + " " + user.getLastName());
}
}
}
In general, you can add elements to a Set to remove duplicates. However, you don't want to add the entire array to the collection in general; you just want to add the individual elements, like so:
public static void main(String[] args) {
Set<User> a = new HashSet<User>();
User[] u = new User[3];
u[0] = new User();
u[0].setFirstName("Mike"); u[0].setLastName("Jordon");
u[1] = new User();
u[1].setFirstName("Jack"); u[1].setLastName("Nicolson");
u[2] = new User();
u[2].setFirstName("Jack"); u[2].setLastName("Nicolson");
// Add each of the users to the Set. Note that there are three.
for (User user : u) {
a.add(u);
}
// Get the results back as an array. Note that this will have two.
User[] duplicatesRemoved = new User[0];
a.toArray(duplicatesRemoved);
}
Hi you can write a method in pp class in order to remove duplicate elements from the user array as follows :
private User[] getUserArrayWithoutDuplicates(User[] a) {
int count = a.length;
Set<User> tempset = new HashSet<User>();
for (int i = 0; i < count; i++) {
User[] user = a;
int arraysize = user.length;
for (int j = 0; j < arraysize; j++)
tempset.add(user[j]);
}
User[] usr = new User[tempset.size()];
Iterator<User> tempIterator = tempset.iterator();
int p = 0;
while (tempIterator.hasNext()) {
User user = tempIterator.next();
usr[p] = new User();
usr[p].setFirstName(user.firstName);
usr[p].setLastName(user.lastName);
p++;
}
return usr;
}
This method will remove the duplicate entries from User array and return the User array without duplicate entries.

Categories