Remove Duplicate Elements in an Array Java
21,869
If you need it to be and return a String[]
array:
Set<String> stringSet = new HashSet<>(Arrays.asList(array));
String[] filteredArray = stringSet.toArray(new String[0]);
Although I'd consider changing the type to a Set<String>
anyway since you're trying to store a list of unique elements.
Author by
Patrick Jean
Updated on November 23, 2022Comments
-
Patrick Jean 12 months
I'm trying to remove duplicate elements from a String array. For example if the input was Yellow, Yellow, Red. The output would be Yellow, Red. What do I put inside the conditional? Is there a remove method in java? Here's the method I made:
public static String [] CompareAndDestroy(String [] array) { String [] newarray = new String [array.length]; for(int i = 0; i<array.length;i++) { for(int j = 0;j<array.length;j++) { if(array[i].compareTo(array[j])==0) { } } } return array; }
-
Abi over 10 years
-
-
Aneez over 9 yearsThis code is really working,,, and one doubt ,, Whats the significance of String[0] in 2nd Line ? ?
-
NilsH over 9 yearsIt's basically just to provide type information to the
toArray
method, as described in the javadoc