I have found a solution to removing duplicates from ArrayList. I have built a custom function that returns an ArrayList and cleans up all duplicates. Here is my code for the custom function.
ArrayList removeDuplicates(ArrayList toCopy) {
ArrayList finalResult = new ArrayList();
for(int i = 0; i < toCopy.size(); i++) {
if(!(finalResult.contains(toCopy.get(i)))) {
finalResult.add(toCopy.get(i));
}
}
return finalResult;
}
Say there is an string that contains “Hello World!”
And the ArrayList is:
0: “Hello”
1: “World!”
2: “Hello World!”
3: “some item”
4: “Hello World!”
5: “Another item”
And after you pass it through the function it will be:
0: “Hello”
1: “World!”
2: “Hello World!”
3: “some item”
4: “Another item”
Keeping only the first “Hello World”.
Here is an simple example
ArrayList exampleal = new ArrayList();
void setup() {
background(100);
size(500, 500);
exampleal.add("yay");
exampleal.add("yay");
exampleal.add("Item");
exampleal.add("Another item");
exampleal.add("Another item");
println(exampleal.size());
println(removeDuplicates(exampleal).size());
}
ArrayList removeDuplicates(ArrayList toCopy) {
ArrayList finalResult = new ArrayList();
for(int i = 0; i < toCopy.size(); i++) {
if(!(finalResult.contains(toCopy.get(i)))) {
finalResult.add(toCopy.get(i));
}
}
return finalResult;
}
In the console where the println() is shown, you will see 5 then 3, because the first one is the original ArrayList, and the second one is the ArrayList where duplicates are deleted. There are two "yay"s and "Another item"s, so only the first ones are kept in the ArrayList.