How to Delete Duplicates From an Array in Java

Written by kevin walker
  • Share
  • Tweet
  • Share
  • Email

Java arrays are the most elementary of data structures, and the easiest to use -- the first data structure every new Java programmer learns about. However, there are some common tasks made difficult. One of them is removing duplicate entries and resizing the array to hold the ones remaining with no null spaces. Fortunately, Java provides a way to strip duplicates with much less work: the LinkedHashSet class. The LinkedHashSet is an advanced data structure with one special trait: it automatically rejects duplicates. To remove the duplicates from the array, you simply move them over to a LinkedHashSet, and move them back.

Skill level:


  1. 1

    Open "Netbeans" and select "File" and "New class."

  2. 2

    Type "psvm" to create a new main method.

  3. 3

    Type the following code into the main method:

    // Define an array that has duplicates.

    Integer[] arr = {1,2,3,2,1};

    // Define a new LinkedHashSet

    LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();

    // Move all the elements in the array into the Hashset

    for (int x : arr) {



    // Resize the array

    arr = new Integer[set.size()];

    // Copy the data back from the hashset

    arr = set.toArray(arr);

  4. 4

    Click "Run."

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.