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
Explain differences between collection api and stream api?
What are the advantages of passing this into a method instead of the current class object itself?
Explain the difference between an Interface and an Abstract class?
Why string is immutable with example?
How can we find the sum of two linked lists using stack in java?
Can we create more than one object singleton class?
Which is better stringbuffer or stringbuilder?
What method is used to specify a container's layout in java programming?
How to perform binary search in java?
Is null false in java?
What is the default execution method in java?
placement papaers of spring computing technology
How do you compare objects in java?
Explain about transient variables in java?
What are different data types?