CodesJava

Easy learning with example program codes

how to eliminate duplicate user defined objects from linkedhashset?


LinkedHashSet:

LinkedHashSet extends HashSet and implements the Set interface. It maintains insertion order for its elements.

Example:

package com.codesjava;
 
import java.util.LinkedHashSet;
 
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;
    }
 
	@Override
	public int hashCode() {
	    System.out.println("In hashcode");
	    return this.getId();
	}
 
	@Override
	public boolean equals(Object obj) {
		Employee e = null;
	    if(obj instanceof Employee){
	        e = (Employee) obj;
	    }
	    System.out.println("In equals");
	    if(this.getId() == e.getId()){
	        return true;
	    } else {
	        return false;
	    }  
	}
}
 
public class Test {
  public static void main(String args[]){
	LinkedHashSet<Employee> hashSet = new LinkedHashSet<Employee>();
	hashSet.add(new Employee(1,"Jai",50000));
	hashSet.add(new Employee(2,"Mahesh",80000));
	hashSet.add(new Employee(3,"Vishal",60000));
	hashSet.add(new Employee(4,"Hemant",64000));
	for(Employee e:hashSet){
            System.out.println(e);
        }
	System.out.println("Add duplicate record:");
	hashSet.add(new Employee(3,"Vishal",60000));
	for(Employee e:hashSet){
            System.out.println(e);
        }
  }
}

Output

In hashcode
In hashcode
In hashcode
In hashcode
Id: 1, Name: Jai, Salary: 50000
Id: 2, Name: Mahesh, Salary: 80000
Id: 3, Name: Vishal, Salary: 60000
Id: 4, Name: Hemant, Salary: 64000
Add duplicate record:
In hashcode
In equals
Id: 1, Name: Jai, Salary: 50000
Id: 2, Name: Mahesh, Salary: 80000
Id: 3, Name: Vishal, Salary: 60000
Id: 4, Name: Hemant, Salary: 64000
Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki