How to eliminate duplicates from an array?

Answer Posted / qim2010

Using HashSet class we can eliminate duplicates from and
array. Here is a simple example

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 + ", ");
}
}
}

Is This Answer Correct ?    5 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

define the terminology association.

589


write a program that list all permutations of ABCDEF in which A appears before B?

1985


Write a regular expression to validate a password. A password must start with an alphabet and followed by alphanumeric characters; its length must be in between 8 to 20.

569


What are the main uses of this keyword?

572


Why java is a platform independent? Explain

510






How do you join strings in java?

492


Is it possible to compare various strings with the help of == operator?

524


Why we use set in java?

494


What restrictions are placed on method overloading in java programming?

547


Is it possible to use string in the switch case?

531


What is package protected in java?

501


Which collection is sorted in java?

521


Can you access the private method from outside the class?

481


Is there a way to increase the size of an array after its declaration?

574


What are three types of loops in java?

563