Java Program to Remove Duplicates from an ArrayList

Отвечено с помощью: GPT-4o-mini отJava Q&A Hub

Вопрос:

Write a Java Program to remove duplicates in an ArrayList.

Ответ:

Certainly! Below is a simple Java program that demonstrates how to remove duplicates from an ArrayList. This program uses a HashSet to filter out duplicates since a HashSet does not allow duplicate values.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class RemoveDuplicates {
    public static void main(String[] args) {
        // Create an ArrayList with some duplicate values
        List<String> listWithDuplicates = new ArrayList<>();
        listWithDuplicates.add("Apple");
        listWithDuplicates.add("Banana");
        listWithDuplicates.add("Apple");
        listWithDuplicates.add("Orange");
        listWithDuplicates.add("Banana");
        listWithDuplicates.add("Grapes");

        System.out.println("Original List: " + listWithDuplicates);

        // Remove duplicates
        List<String> listWithoutDuplicates = removeDuplicates(listWithDuplicates);

        System.out.println("List after removing duplicates: " + listWithoutDuplicates);
    }

    public static List<String> removeDuplicates(List<String> list) {
        // Use a HashSet to remove duplicates
        HashSet<String> set = new HashSet<>(list);
        // Convert the HashSet back to an ArrayList
        return new ArrayList<>(set);
    }
}

Explanation:

  1. Import Statements: We import ArrayList, HashSet, and List from the java.util package.
  2. Main Method: We create an ArrayList called listWithDuplicates and populate it with some strings, including duplicates.
  3. Remove Duplicates: We call the removeDuplicates method, which takes the original list as an argument.
  4. Using HashSet: Inside the removeDuplicates method, we create a HashSet from the list. This automatically removes any duplicate entries.
  5. Return a New List: We convert the HashSet back to an ArrayList and return it.
  6. Output: Finally, we print both the original list and the list after duplicates have been removed.

Output:

When you run the program, you should see output similar to the following:

Original List: [Apple, Banana, Apple, Orange, Banana, Grapes]
List after removing duplicates: [Apple, Banana, Orange, Grapes]

Note that the order of elements in the resulting list may vary because HashSet does not maintain the order of elements. If you need to maintain the original order, you can use a LinkedHashSet instead of a HashSet.