

This article contains example of how to remove duplicate value from array in java with different different methods like using Set, using stream dicstinct funcation.
Table of Contents
Example 1 : Remove duplicate value from array using Set
Set is contains unique and unorder values. Using Set Collection we can remove duplicate values, Let me clear here Set internally used HashMap as Key parameters. Its contains all characteristics of HashMap Key attributes.
Using Java 7 traditional:
String[] names = {"Java", "C", "PHP", "Java", "Net", "C"}; HashSet<String> uniqueNames = new HashSet<>(); for (String name : names) { uniqueNames.add(name); // its will remove duplicate name because Set will set only unique value } for (String name : uniqueNames) { System.out.println(name); }
Using Java 8 Stream
String[] names = {"Java", "C", "PHP", "Java", "Net", "C"}; java.util.Set<String> uniqueNames = Stream.of(names).collect(Collectors.toSet()); uniqueNames.forEach(System.out::println);
Output:
Java C PHP Net
Example 2: Remove duplicate value from Array using Stream distinct
In Java 8 provide stream using that we can perform so many operation easily. distinct()
is function which return unique object from Stream,
after distinct we will convert those result to list.
String[] names = {"Java", "C", "PHP", "Java", "Net", "C"}; List<String> uniqueNames = Stream.of(names).distinct().collect(Collectors.toList()); uniqueNames.forEach(System.out::println);
Output:
Java C PHP Net
Refer HashSet , java 8 stream for more details about HashSet and java 8 stream.
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.