Java Program to Remove Repeated Element from An ArrayList

JavaCampus InterviewServer Side ProgrammingProgramming

In this article, we will understand how to remove repeated element from an array-list. The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.

Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

Below is a demonstration of the same −

Suppose our input is

The list is defined as: [Java, Scala, JavaScript, Scala]

The desired output would be

The list after removing the duplicates is: [Java, Scala, JavaScript]

Algorithm

Step 1 - START
Step 2 - Declare an ArrayList namely input_list and declare a set namely temp.
Step 3 - Define the values.
Step 4 - Convert the list to a set
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      ArrayList<String> input_list = new ArrayList<String>();
      input_list.add("Java");
      input_list.add("Scala");
      input_list.add("JavaScript");
      input_list.add("Scala");
      System.out.println("The list is defined as: " + input_list);
      Set<String> temp = new LinkedHashSet<>(input_list);
      List<String> result_list = new ArrayList<>(temp);
      System.out.println("The list after removing the duplicates is: " + result_list);
   }
}

Output

The list is defined as: [Java, Scala, JavaScript, Scala]
The list after removing the duplicates is: [Java, Scala, JavaScript]

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming.

import java.util.*;
public class Demo {
   static void remove_duplicates(ArrayList<String> input_list){
      Set<String> temp = new LinkedHashSet<>(input_list);
      List<String> result_list = new ArrayList<>(temp);
      System.out.println("The list after removing the duplicates is: " + result_list);
   }
   public static void main(String args[]) {
      ArrayList<String> input_list = new ArrayList<String>();
      input_list.add("Java");
      input_list.add("Scala");
      input_list.add("JavaScript");
      input_list.add("Scala");
      System.out.println("The list is defined as: " + input_list);
      remove_duplicates(input_list);
   }
}

Output

The list is defined as: [Java, Scala, JavaScript, Scala]
The list after removing the duplicates is: [Java, Scala, JavaScript]
raja
Updated on 29-Mar-2022 12:45:50

Advertisements