I have a ArrayList<CustomObject>
as ArrayList<Names>
in my project. The Names pojo contains name and image fields as follows:
Names.java
public class Names {
private String name;
private String image;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Names(String name, String image) {
this.name = name;
this.image = image;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return name;
}
}
I am adding values for the fields as follows:
ArrayList<Names> menu = new ArrayList<Names>();
menu.add(new Names("chandru","image1"));
menu.add(new Names("vikki","image2"));
menu.add(new Names("karthick","image3"));
menu.add(new Names("chandru","image4"));
menu.add(new Names("karthick","image5"));
menu.add(new Names("chandru","image6"));
menu.add(new Names("karthick","image7"));
menu.add(new Names("vikki","image8"));
menu.add(new Names("karthick","image9"));
menu.add(new Names("harish","image10"));
menu.add(new Names("vivek","image11"));
menu.add(new Names("harish","image12"));
My requirement:
Now all my requirement is to remove the repeated names contains in the ArrayList. I tried several methods like to remove duplicates as follows:
Method I: Using HashSet
Adding values into the HashSet and assigning back those values into new ArrayList<Names>
named al
.
ArrayList<Names> al = new ArrayList<Names>();
Set<Names> hs = new HashSet<Names>();
hs.addAll(menu);
al.clear();
al.addAll(hs);
System.out.println(al);
Output of Method I:
[karthick, vikki, karthick, karthick, chandru, vivek, vikki, chandru, harish, harish, karthick, chandru]
Expected Output to be:
Values after removing duplicates:
[karthick, vikki,chandru, vivek, harish]
I am also posting my entire class for your reference
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class Sample {
public static void main(String[] args) {
ArrayList<Names> menu = new ArrayList<Names>();
menu.add(new Names("chandru","image"));
menu.add(new Names("vikki","image"));
menu.add(new Names("karthick","image"));
menu.add(new Names("chandru","image"));
menu.add(new Names("karthick","image"));
menu.add(new Names("chandru","image"));
menu.add(new Names("karthick","image"));
menu.add(new Names("vikki","image"));
menu.add(new Names("karthick","image"));
menu.add(new Names("harish","image"));
menu.add(new Names("vivek","image"));
menu.add(new Names("harish","image"));
ArrayList<Names> al = new ArrayList<Names>();
Set<Names> hs = new HashSet<Names>();
hs.addAll(menu);
al.clear();
al.addAll(hs);
System.out.println(al);
}
}
Please help me to resolve by issue which I am facing to remove duplicates from the list. Any kind of suggestions and solutions would be much helpful for me. Thanks in advance.