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.

Share:
21,869
Patrick Jean
Author by

Patrick Jean

Updated on November 23, 2022

Comments

  • Patrick Jean
    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;
    }
    
  • Aneez
    Aneez over 9 years
    This code is really working,,, and one doubt ,, Whats the significance of String[0] in 2nd Line ? ?
  • NilsH
    NilsH over 9 years
    It's basically just to provide type information to the toArray method, as described in the javadoc