Fetch unique object values from ArrayList without looping

 

Today we will discuss on simple Java Collection interview question as how to fetch unique object values from ArrayList without looping through ArrayList. We can achieve by @Overriding hascode() and equals() method in our class.

Example:
 
       Lets assume we have box full of pencils with various colors like (red, green, blue, yellow etc.,) around 2000 pencils. We need to find total no. of colors in the box. 


       Lets assume box is the ArrayList and Pencil is the class with member variable called color. Below sample code is the one of the way we can fetch unique color of pencils in the ArrayList without looping.




 
 
 
public class Pencil{
 private String color;
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public Pencil(String color){
        this.color = color;
    }
    @Override
    public int hashCode() {
     return 0;
    }     
    @Override
    public boolean equals(Object obj) {
        return ((Pencil)obj).color == this.color;
    }
}


       Above Pencil class contains color member variable, constructor, getter and setter method. Along with these methods we do have @Override method implementation for hascode() and equals() which will be used to find the color of each object stored in ArrayList and while storing in HashSet will elimate duplicate value from below code.



 public class PencilColors {
 public static void main(String[] args) {
  ArrayList<Pencil> box = new ArrayList<Pencil>();
        box.add(new Pencil("red"));
        box.add(new Pencil("green"));
        box.add(new Pencil("blue"));
        box.add(new Pencil("red"));
        box.add(new Pencil("blue"));
        Set<Pencil> list = new HashSet<Pencil>(box);
        Iterator<Pencil> itr = list.iterator();
        while(itr.hasNext()){
            Pencil pencil = itr.next();
            System.out.println(pencil.getColor());
        }
    }
}



OUTPUT:

blue
green
red


Hope you are clear now how to fetch unique values from ArrayList without looping just by using Java Collections. Please drop your comments below.




1 comment:
Write comments