How to Use LinkedHashset to Prevent Duplication in Java


In this example we will show how to avoid duplicate user defined objects from LinkedHashSet.

Source Code

1)ForExample

package com.beginner.examples;

import java.util.HashMap;
import java.util.Set;
 
public class ForExample{
     
    private String name;
    private int number;
     
    public ForExample(String nm, int num){
        this.name = nm;
        this.number = num;
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    
    public String toString(){
        return "name: " + name + "  number: " + number;
    }
    // implement equals() method at the user defined objects
    public boolean equals(Object obj){
        ForExample e = (ForExample) obj;
        return (e.name.equals(this.name) && e.number == this.number);
    }
    // implement hashcode() method at the user defined objects
    public int hashCode(){
        int hashcode = 0;
        hashcode = number*10;
        hashcode += name.hashCode();
        return hashcode;
    }
    
}

2)DuplicateKeyExample3

package com.beginner.examples;

import java.util.LinkedHashSet;
import java.util.Set;
 
public class DuplicateKeyExample3 {
 
    public static void main(String a[]){
         
        LinkedHashSet set = new LinkedHashSet();
        set.add(new ForExample("java", 110));
        set.add(new ForExample("c++", 20));
        set.add(new ForExample("python", 75));
        // print the set
        printMap(set);
        ForExample key = new ForExample("java", 110);
        set.add(key);
        System.out.println("After adding dulicate key:");
        // print the set
        printMap(set);
    }
     
    public static void printMap(LinkedHashSet set){
         
        for(ForExample p:set){
            System.out.println(p);
        }
    }
}

Output:

name: java  number: 110
name: c++  number: 20
name: python  number: 75
After adding dulicate key:
name: java  number: 110
name: c++  number: 20
name: python  number: 75

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments