How do I remove duplicate element from array?

Category: java.util, viewed: 23634 time(s).

This example demonstrate you how to remove duplicate elements from an array using the HashSet class.

package org.kodejava.example.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ArrayRemoveDuplicate {
    public static void main(String[] args) {
        //
        // A string array with duplicate values
        //
        String[] data = {"A", "C", "B", "D", "A", "B", "E", "D", "B", "C"};
        System.out.println("Original array         : " + Arrays.toString(data));

        //
        // Convert it to list as we need the list object to create a set object.
        // A set is a collection object that cannot have a duplicate values, so
        // by converting the array to a set the duplicate value will be removed.
        //
        List<String> list = Arrays.asList(data);
        Set<String> set = new HashSet<String>(list);

        System.out.print("Remove duplicate result: ");
        
        //
        // Create an array to convert the Set back to array. The Set.toArray()
        // method copy the value in the set to the defined array.
        //
        String[] result = new String[set.size()];
        set.toArray(result);
        for (String s : result) {
            System.out.print(s + ", ");
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats