[Java] How to remove all duplicates from an array?
I want to remove all duplicate elements from an existing array, how can we do that in Java?
1 Answer
4 years ago by Eleven
We can use distinct on streams to remove the duplicates from an array. Following code shows how to do that
import java.util.Arrays;
public class JavaArrays {
public static void main(String[] args) {
String[] colors = { "blue", "red", "green", "yellow", "blue" };
String[] nonDuplicateColors = Arrays.stream(colors).distinct().toArray(String[]::new);
System.out.println(Arrays.toString(nonDuplicateColors));
}
}
Output:
[blue, red, green, yellow]
Try online here: https://onecompiler.com/java/3xmtfhsm6
4 years ago by Karthik Divi