Java Program to Remove Duplicates from an Array List

JavaCampus InterviewServer Side ProgrammingProgramming

In this article, we will understand how to remove duplicates from an array list. A list is an ordered collection that allows us to store and access elements sequentially. It contains the index-based methods to insert, update, delete and search the elements. It can also have the duplicate elements.

Below is a demonstration of the same −

Suppose our input is

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

The desired output would be

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

Algorithm

Step 1 - START
Step 2 - Declare a list namely input_list and a Set namely result_set.
Step 3 - Define the values.
Step 4 - Convert the input list to a set as set cannot have duplicate values.
Step 5 - Display the result
Step 6 - Stop

Example 1

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

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class Demo {
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      List<String> input_list = new ArrayList<String>();
      input_list.add("Java");
      input_list.add("Scala");
      input_list.add("Python");
      input_list.add("Java");
      System.out.println("The list is defined as: " +input_list.toString());
      Set<String> result_set = new LinkedHashSet<String>(input_list);
      System.out.println("The list after removing the duplicates: "+result_set);
   }
}

Output

The required packages have been imported
The list is defined as: [Java, Scala, Python, Java]
The list after removing the duplicates: [Java, Scala, Python]

Example 2

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

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class Demo {
   static void remove_duplicates(List<String> input_list){
      Set<String> result_set = new LinkedHashSet<String>(input_list);
      System.out.println("The list after removing the duplicates: "+result_set);
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      List<String> input_list = new ArrayList<String>();
      input_list.add("Java");
      input_list.add("Scala");
      input_list.add("Python");
      input_list.add("Java");
      System.out.println("The list is defined as: " +input_list.toString());
      remove_duplicates(input_list);
   }
}

Output

The required packages have been imported
The list is defined as: [Java, Scala, Python, Java]
The list after removing the duplicates: [Java, Scala, Python]
raja
Updated on 29-Mar-2022 12:31:12

Advertisements