So I searched for this "problem" and only came accross questions asking how to remove real duplicates from a list. But what I want is to remove every Object being equal to another Object in the list according to a custom .equals() method.
Here I have an example class with the equals() method being overriden:
private static class Test {
int x;
float[] data;
public Test(int x, float[] data) {
this.x = x;
this.data = data;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Test) {
Test compare = (Test) obj;
if (
compare.x == this.x &&
Arrays.equals(compare.data, this.data)
) {
return true;
}
}
return false;
}
}
Now the following would not be the same of course (no duplicates which could be eliminated by a HashMap for example):
Test test1 = new Test(3, new float[]{0.1f, 0.4f});
Test test2 = new Test(3, new float[]{0.1f, 0.4f});
But in my case they are a duplicate and I want to keep only one of them.
I came up with this approach:
Test test1 = new Test(3, new float[]{0.1f, 0.4f});
Test test2 = new Test(3, new float[]{0.1f, 0.4f});
Test test3 = new Test(2, new float[]{0.1f, 0.5f});
List<Test> list = new ArrayList<>();
list.add(test1);
list.add(test2);
list.add(test3);
Set<Test> noDuplicates = new HashSet<>();
for (Test testLoop : list) {
boolean alreadyIn = false;
for (Test testCheck : noDuplicates) {
if (testLoop.equals(testCheck)) {
alreadyIn = true;
break;
}
}
if (!alreadyIn) {
noDuplicates.add(testLoop);
}
}
And this works fine but is not that nice in terms of performance. (In my case it is important because the list size can be big)
Now my question: Is there a more convenient approach to achieve this?