Remove elements with Condition: preserve the original order

Problem Statement: Write a Java program to remove duplicates from an ArrayList while preserving the original order.

Here’s a Java program that demonstrates how to remove duplicates from an ArrayList while preserving the original order. I’ll provide an explanation of the program’s logic.

package com.javacodepoint.collection;

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

public class RemoveDuplicatesPreserveOrderDemo {

	public static void main(String[] args) {
		List<Integer> numbers = new ArrayList<>();
		numbers.add(10);
		numbers.add(20);
		numbers.add(30);
		numbers.add(20);
		numbers.add(40);
		numbers.add(10);

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

		// Removing duplicates while preserving order
		List<Integer> uniqueNumbers = removeDuplicatesPreserveOrder(numbers);

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

	// Method to remove duplicates while preserving order
	public static <T> List<T> removeDuplicatesPreserveOrder(List<T> list) {
		HashSet<T> seen = new LinkedHashSet<>();
		List<T> uniqueList = new ArrayList<>();

		for (T element : list) {
			if (seen.add(element)) {
				uniqueList.add(element);
			}
		}

		return uniqueList;
	}
}

OUTPUT:

Original List: [10, 20, 30, 20, 40, 10]
List after removing duplicates: [10, 20, 30, 40]

Explanation:

  1. Creating the List: We create an ArrayList named numbers and populate it with some integers, including duplicates.
  2. Printing the Original List: We print the contents of the numbers list using System.out.println().
  3. Removing Duplicates while Preserving Order: We call the removeDuplicatesPreserveOrder() method to remove duplicates from the numbers list while preserving the original order.
  4. removeDuplicatesPreserveOrder() Method: This method uses two data structures to achieve the goal. It uses a HashSet (seen) to keep track of elements that have been seen, and a new ArrayList (uniqueList) to store the unique elements in the order they appear.
  5. Iterating Through the List: We iterate through the list using a enhanced for loop. For each element, we check if it’s not already in the seen set (meaning it’s unique). If it’s unique, we add it to both the seen set and the uniqueList.
  6. Returning the List without Duplicates: The method returns the uniqueList, which contains the elements from the input list without duplicates, while preserving the original order.

By using a HashSet to keep track of seen elements and an ArrayList to store unique elements in order, the program effectively removes duplicates from the ArrayList while maintaining the original element order.

See also: Create a stack using an ArrayList.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *