Solution: Remove duplicates from ArrayList

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.

2 Likes

Hi @ubuntu-in-a-nutshell ,

Wouldn’t it be easier if you used a Map Interface? Maps work in key, value pairs and don’t allow duplicate keys. You could easily transfer the ArrayList to a map, where you could assign the value has the frequency of the key appearing in the ArrayList!, if only need the keys without duplicate, just retrieve the keys :wink:
Here is an example:

And below you can find some documentation as well!

Map Documentation Links

Map (Java Platform SE 8 )
Map Interface in Java - GeeksforGeeks

Best regards!

2 Likes

@MiguelSanches Yeah, I have heard of HashMaps. This post is just for anyone who wanted an ArrayList solution specifically.

1 Like