Java String Handling

Java String array remove duplicates example

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

How to remove duplicates from String array in Java?

There are several ways using which you can remove duplicates from 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 String array as given below.

Output

We first converted array to List using asList method of Arrays class. Then we created a new LinkedHashSet 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 toArray method.

2) Java String array remove duplicates using ArrayList

We can also use ArrayList to remove duplicates from an array as given below.

Output

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

3) Java String array remove duplicates using Java 8 Stream

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

Output

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

 

Join 1000+ fellow learners! Enter your email address below: