I have a List where some Objects are being stored.I would like to remove an object from list with certain attribute already not exists.My sample code is, here please help me.
public class Mysamples {
private void example() {
List<SomeType> listWithDuplicates = new ArrayList<SomeType>();
SomeType someObject1 = new SomeType("hello", "1");
SomeType someObject2 = new SomeType("hello", "2");
}
private void removeDuplicates(List<SomeType> listWithDuplicates) {
/* Set of all attributes seen so far */
Set<String> attributes = new HashSet<String>();
/* All confirmed duplicates go in here */
List duplicates = new ArrayList<SomeType>();
for (SomeType x : listWithDuplicates) {
if (attributes.contains(x.getName()))
{
duplicates.add(x);
}
attributes.add(x.getName());
}
System.out.println(duplicates);
// System.out.println(attributes);
}
public static void main(String[] args) {
// TODO code application logic here
List<SomeType> listWithDuplicates = new ArrayList<SomeType>();
SomeType someObject1 = new SomeType("hello", "1");
SomeType someObject2 = new SomeType("hello", "2");
SomeType someObject3 = new SomeType("hello", "1");
SomeType someObject4 = new SomeType("hello1", "2");
SomeType someObject5 = new SomeType("hello1", "1");
SomeType someObject6 = new SomeType("hello2", "2");
listWithDuplicates.add(someObject1);
listWithDuplicates.add(someObject2);
listWithDuplicates.add(someObject3);
listWithDuplicates.add(someObject4);
listWithDuplicates.add(someObject5);
listWithDuplicates.add(someObject6);
Mysamples s = new Mysamples();
s.removeDuplicates(listWithDuplicates);
}
}
*The out put is*
[SomeType{name=hello, id=2}, SomeType{name=hello, id=1}, SomeType{name=hello1, id=1}]
but i want the out put like
[SomeType{name=hello, id=1,SomeType{name=hello, id=2}, SomeType{name=hello, id=1}} SomeType{name=hello1, id=2},SomeType{name=hello1, id=1}]]