An Easier Way to Remove the Duplicates From the Front and Keep the Stability of the Array of Elements Using Arraylist in Java

Nickson Joram
Javarevisited
Published in
2 min readApr 28, 2021

We have seen the same problem and its solution using a long step using Array Data Structure in this article. We are going to solve the same problem in a simplified way using the ArrayList Data Structure.

Recommended: Read about the Arrays in Java and Data Structures before continuing if needed.

Image by Author

As we discussed in our previous article, let’s solve the same problem but using the ArrayList Data Structure.

int [] array = {1, 1, 2, 3, 3, 4, 1, 3};
removeDuplicates(array);

This is our original array. And we are calling the method removeDuplicates and passing the original array as a parameter. We then create a method like this.

public static void removeDuplicates (int [] arg) { //Solution }

After that, we create an ArrayList like this.

List<Integer> chars = new ArrayList<>();

We then traverse through the original array using a for loop like this.

for(int i = 0; i < arg.length; i++) { //Solution }

Then we get the ith element using a new variable. This is optional.

int temp = arg[i];

Then we check the existence of this element in the ArrayList as follows.

if(chars.contains(temp)) { //Solution }

If it has the element we have to do the following checks.

if(chars.size() == 1) {
chars.set(0, temp);
} else {
chars.remove(new Integer(temp));
chars.add(temp);
}

Why we have to check the size?

if(chars.size() == 1) { //Solution }

Try to implement without that check and understand.

And in the else part, that means, the checked element is not in the ArrayList, we have to add it simply like this.

else {
chars.add(temp);
}

After that, we can print the ArrayList and that is our expected result.

System.out.println(Arrays.toString(chars.toArray()));

For this problem, the output will be like

[2, 4, 1, 3]

As we discussed in the previous article, this is very easier than that way of solving the same problem.

Try to implement some other better and alternate ways to solve this problem and share with me.

Hope the article can help. Share your thoughts too.

--

--