Skip to content

Java String array remove duplicates example

Java String array remove duplicates example shows how to remove duplicates from String array in Java. The example also shows how to remove duplicates from String array using Java 8 stream.

How to remove duplicates from the String array in Java?

There are several ways using which you can remove duplicates from the String array in Java as given below.

1) Java String array remove duplicates using Set (HashSet/LinkedHashSet)

One of the properties of the Set is that it does not allow duplicate elements. We can use this property to remove duplicates from an array as given below.

Output

We first converted an array to List using the asList method of the Arrays class. Then we created a new LinkedHashSet object and added all elements of the List to it thus removing all the duplicate strings. Finally, we created a new array from the LinkedHashSet using the toArray method. You can also use the HashSet class instead of the LinkedHashSet, but in that case order of the elements may not be maintained.

2) Using an ArrayList

We can also use the ArrayList class to remove the duplicates as given below.

Output

We first created an empty ArrayList object. Next, we looped through the array and checked if the array element already exists in the ArrayList using the contains method. If it did not exist, we added the element to ArrayList thus skipping all duplicate elements. Finally, we converted the ArrayList to array using the toArray method.

3) Using Java 8 Stream

If you are using Java 8, you can use the stream along with distinct to remove duplicates as given below.

Output

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.