Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Program to Remove a Specific Element From a Collection
Next article icon

Java Program To Remove All The Duplicate Entries From The Collection

Last Updated : 03 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

As we know that the HashSet contains only unique elements, ie no duplicate entries are allowed, and since our aim is to remove the duplicate entries from the collection, so for removing all the duplicate entries from the collection, we will use HashSet.The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. The class also offers constant time performance for the basic operations like add, remove, contains, and size assuming that the hash function disperses the elements properly among the buckets. HashSet is generally used to keep a check on whether an element is present in a list or not.

Note: Since we are using HashSet so the insertion order will not be preserved and every time we run the code we are going to get some different output (order of elements will be different). So If we want to preserve the order of elements while inserting, then we are supposed to use LinkedHashSet.

There are basically two methods to remove the duplicate entries from the collection:

  1. Using HashSet
  2. Using LinkHashSet

Now Let's see the implementation using the java program to remove the duplicate entries by using both the methods one by one:-

1. Using HashSet

Java
// Java Program to remove the duplicate entries from // collection using HashSet  import java.util.ArrayList; import java.util.Collection; import java.util.HashSet;  class GFG {     public static void main(String[] args)     {         // making the collection object         Collection<String> collection = new ArrayList<>();          // adding the elements to the collection         collection.add("Geeks");         collection.add("For");         collection.add("Geeks");         collection.add("Internship");         collection.add("Internship");         collection.add("2021");         collection.add("2021");          // Displaying the collection elements         System.out.println(             "Displaying the initial collection\n");         System.out.println(collection);          // HashSEt for deleting duplicate entries         // in the collection by passing collection         // in the constructor of the HashSet         HashSet<String> hashSet = new HashSet<>(collection);          // Displaying the HashSet         System.out.println("\nDisplaying the HashSet\n");         System.out.println(hashSet);          // clearing all the elements of the collection         collection.clear();          // adding all the elements back         // to the collection from HashSet         collection.addAll(hashSet);          // Displaying the collection         System.out.println(             "\nDisplaying the collection after deleting duplicates entries\n");         System.out.println(collection);     } } 


Output: 

Displaying the initial collection

[Geeks, For, Geeks, Internship, Internship, 2021, 2021]

Displaying the HashSet

[Geeks, For, 2021, Internship]

Displaying the collection after deleting duplicates entries

[Geeks, For, 2021, Internship]

2.  Using LinkedHashSet

Java
// Java Program to remove the duplicate entries from // collection using LinkedHashSet  import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet;  class GFG {     public static void main(String[] args)     {         // making the collection object         Collection<String> collection = new ArrayList<>();          // adding the elements to the collection         collection.add("Geeks");         collection.add("For");         collection.add("Geeks");         collection.add("Internship");         collection.add("Internship");         collection.add("2021");         collection.add("2021");          // Displaying the collection elements         System.out.println(             "Displaying the initial collection\n");         System.out.println(collection);          // LinkedHashSet for deleting duplicate entries         // in the collection by passing collection         // in the constructor of the HashSet         LinkedHashSet<String> hashSet             = new LinkedHashSet<>(collection);          // Displaying the HashSet         System.out.println("\nDisplaying the HashSet\n");         System.out.println(hashSet);          // clearing all the elements of the collection         collection.clear();          // adding all the elements back         // to the collection from HashSet         collection.addAll(hashSet);          // Displaying the collection         System.out.println(             "\nDisplaying the collection after deleting duplicates entries\n");         System.out.println(collection);     } } 

Output:

Displaying the initial collection

[Geeks, For, Geeks, Internship, Internship, 2021, 2021]

Displaying the HashSet

[Geeks, For, Internship, 2021]

Displaying the collection after deleting duplicates entries

[Geeks, For, Internship, 2021]


Next Article
Java Program to Remove a Specific Element From a Collection
author
le0
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Java Programs
  • Technical Scripter 2020
  • Java-Collections
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • Java Program to Remove Duplicate Elements From the Array
    Given an array, the task is to remove the duplicate elements from an array. The simplest method to remove duplicates from an array is using a Set, which automatically eliminates duplicates. This method can be used even if the array is not sorted. Example: [GFGTABS] Java // Java Program to Remove Dup
    6 min read
  • Java Program to Remove a Specific Element From a Collection
    remove() method is used to remove elements from a collection. It removes the element at the specified position in this list. Shifts any subsequent elements to the left by subtracts one from their indices. In simpler words, the remove() method is used for removing the element from a specific index fr
    3 min read
  • Java Program to Remove Duplicate Entries from an Array using TreeSet
    Features of TreeSet is the primary concern it is widely used in remove duplicates in the data structure as follows: TreeSet implements the SortedSet interface. So, duplicate values are not allowed and will be leftovers.Objects in a TreeSet are stored in a sorted and ascending order.TreeSet does not
    3 min read
  • Java Program to Find the Intersection Between Two Collection
    Collection means a set of different classes and interfaces are group together into a single unit that has similar functions are called collection and framework we know very that provides a predefined architecture to represents and manipulate collections in java. Here we will be discussing discuss ou
    4 min read
  • How to Prevent the Addition of Duplicate Elements to the Java ArrayList?
    Ever wondered how you can make an ArrayList unique? Well, in this article we'll be seeing how to prevent the addition of duplicates into our ArrayList. If an ArrayList have three duplicate elements, but at the end, only the ones which are unique are taken into the ArrayList and the repetitions are n
    3 min read
  • How to Remove Duplicate Elements from the Vector in Java?
    Using LinkedHashSet and TreeSet, duplicate elements are removed. Because the LinkedHashSet and TreeSet do not accept duplicate elements. Example: Input : vector = [1, 2, 3, 4, 2, 4] Output: vector = [1, 2, 3, 4] Input : vector = [a, b, a, c, d, a] Output: vector = [a, b, c, d]Approach 1: Using Linke
    3 min read
  • Java Program For Removing Duplicates From An Unsorted Linked List
    Given an unsorted Linked List, the task is to remove duplicates from the list. Examples: Input: linked_list = 12 -> 11 -> 12 -> 21 -> 41 -> 43 -> 21 Output: 12 -> 11 -> 21 -> 41 -> 43 Explanation: Second occurrence of 12 and 21 are removed. Input: linked_list = 12 ->
    6 min read
  • Java Program For Removing Duplicates From A Sorted Linked List
    Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43-
    8 min read
  • How to Remove the First Entry or Last Entry from the Java TreeMap?
    TreeMap is the implementation class of the Map interface. It allows the objects to be sorted according to the keys and sorting can be natural sorting or you can use a comparator. Insertion order is also not preserved in Tree Map. Syntax: TreeMap<String,Integer> map = new TreeMap<>();In t
    6 min read
  • Java Program To Recursively Remove All Adjacent Duplicates
    Given a string, recursively remove adjacent duplicate characters from the string. The output string should not have any adjacent duplicates. See the following examples. Examples: Input: azxxzy Output: ay First "azxxzy" is reduced to "azzy". The string "azzy" contains duplicates, so it is further red
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences