Java 8 streams – How to remove duplicate elements from array

Let’s see how we can remove duplicate elements from array using.


For example having the input

String[] input = {"Ann", "Tom", "George", "Tom", "Philip", "Bob", "Ann"};

Produce the output:

{"Ann", "Tom", "George", "Philip", "Bob"} 

In java 7 way:
we can use Set to collect all the unique elements

Set set = new HashSet<>();
Collections.addAll(set, input);
for (String element : set) {
    System.out.print(element+" ");
}
//output
Ann Tom George Bob Philip 

Java 8 streams
We can do the same task using java 8 streams

String[] unique = Arrays.stream(input).distinct().toArray(String[]::new);
for (String anUnique : unique) {
    System.out.println(anUnique+" ");
}

//output
Ann Tom George Philip Bob