Friday 1 August 2014

Convert List to Set

Simplest way to convert List to set is pass the List instance to the Set Constructor.

Ex:
Set mySet = new HashSet<> (myList)

But one thing to remember is, Set won't allow duplicates. Duplication is identified by using in combination with equals and hashCode method. If you don't override both the methods then duplicates store into the set.

Ex: Without overriding equals and hashCode
public class Employee{
    String name;
    Integer id;
    
    Employee(int id, String name){
        this.name = name;
        this.id = id;
    }
    
    @Override
    public String toString(){
        return id +" " + name;
    }
}

import java.util.*;

public class ListToSet {
    public static void main(String args[]){
        List<Employee> myList = new ArrayList<> ();
        Set<Employee> mySet;
        
        Employee e1 = new Employee(1, "Krishna");
        Employee e2 = new Employee(2, "Arjun");
        Employee e3 = new Employee(1, "Krishna");
        
        myList.add(e1);
        myList.add(e2);
        myList.add(e3);
        
        mySet = new HashSet<> (myList);
        
        Iterator<Employee> iter = mySet.iterator();
        
        while(iter.hasNext()){
            System.out.println(iter.next());
        }
        
    }
}

Output
1 Krishna
1 Krishna
2 Arjun

As you observe the output, Employee with id '1' and name 'Krishna' stored twice in the set. To resolve the issue Employee class must override hashCode and equals methods.

Ex: Overriding equals and hashCode
import java.util.Objects;

public class Employee{
    String name;
    Integer id;
    
    Employee(int id, String name){
        this.name = name;
        this.id = id;
    }
    
    @Override
    public String toString(){
        return id +" " + name;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 29 * hash + Objects.hashCode(this.name);
        hash = 29 * hash + Objects.hashCode(this.id);
        return hash;
    }
    
    @Override
    public boolean equals(Object obj){
        if(obj!=null)
            if(obj instanceof Employee){
                Employee emp = (Employee) obj;
                boolean a = Objects.equals(id, emp.id);
                boolean b = (name == null ? emp.name == null : name.equals(emp.name));
                return ( a && b);
            }
        return false;                
    }
}

Run ListToSet again, then no duplicates are stored to the Set.

Related Links




                                                             Home

No comments:

Post a Comment