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

what are three ways in which a thread can enter the waiting state? : Java thread

767


How does linkedhashmap work in java?

690


What are disadvantages of java?

740


Explain about wait() method?

770


Why do we need autoboxing in java?

746


What do you mean by singleton class in java?

679


What is java and why do we need it? Explain

790


Why do we use string?

773


What is initial size of arraylist in java?

766


What is the difference between jdk, jre, and jvm?

785


What is try-with-resources in java?

832


What flag up means?

787


How many functional interfaces does java 8 have?

790


Can constructor be protected in java?

710


Tell me the latest versions in java related areas?

820