Avoid duplicate user defined objects in TreeSet

Example

package com.w3spoint;
 
import java.util.Comparator;
import java.util.TreeSet;
 
class Employee{    
    private String name;
    private int salary;
    private int id;
 
    public Employee(int id, String name, int salary){
    	this.id = id;
        this.name = name;
        this.salary = salary;
    }
 
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String toString(){
        return "Id: "+this.id+", Name: "+this.name+", Salary: "+this.salary;
    }
}
 
class EmployeeComp implements Comparator<Employee>{	 
    @Override
    public int compare(Employee e1, Employee e2) {
        if(e1.getId() == e2.getId()){
            return 0;
        } if(e1.getId() < e2.getId()){
            return 1;
        } else {
            return -1;
        }
    }
}
 
public class Test {
  public static void main(String args[]){
	TreeSet<Employee> treeSet = new TreeSet<Employee>(new EmployeeComp());
	treeSet.add(new Employee(1,"Jai",50000));
	treeSet.add(new Employee(2,"Mahesh",80000));
	treeSet.add(new Employee(3,"Vishal",60000));
	treeSet.add(new Employee(4,"Hemant",64000));
	for(Employee e:treeSet){
            System.out.println(e);
        }
	System.out.println("Add duplicate record:");
	treeSet.add(new Employee(3,"Vishal",60000));
	for(Employee e:treeSet){
            System.out.println(e);
        }
   }
}

Output

Id: 4, Name: Hemant, Salary: 64000
Id: 3, Name: Vishal, Salary: 60000
Id: 2, Name: Mahesh, Salary: 80000
Id: 1, Name: Jai, Salary: 50000
Add duplicate record:
Id: 4, Name: Hemant, Salary: 64000
Id: 3, Name: Vishal, Salary: 60000
Id: 2, Name: Mahesh, Salary: 80000
Id: 1, Name: Jai, Salary: 50000
Please follow and like us:
Content Protection by DMCA.com