In this article, we will discuss how to remove duplicate elements from Array
Also read,
- Java – Different ways to remove duplicate elements from Arrays
- Java – How to find duplicate in String Arrays ?
1. Remove duplicate elements from Arrays :
- Initially, there is a String[] Array with duplicate elements
- First step is to iterate through original String[] Array with duplicates
- Use distinct() method of Stream API to remove duplicate String elements and then invoke toArray(); method to convert/result into Object[] Array
- Finally, iterate/print Array with unique elements using forEach() method of Stream API
RemoveDuplicateUsingStream.java
package net.bench.resources.java.arrays;
import java.util.Arrays;
public class RemoveDuplicateUsingStream {
// main() method - entry point for JVM
public static void main(String[] args) {
// 1. initialize an Arrays with few duplicate values
String[] strArray = {
"Meta",
"Apple",
"Amazon",
"Netflix",
"Apple", // duplicate
"Google",
"Netfilx" // duplicate
};
// 2. Iterating original Arrays using forEach loop
System.out.println("1. Original Array with duplicates :\n");
Arrays.stream(strArray).forEach(name -> System.out.println(name));
// 3. remove duplicates from Arrays using Java 8 Stream
Object[] uniqueArrays = Arrays.stream(strArray).distinct().toArray();
// 4. Iterating unique Arrays using forEach loop
System.out.println("\n\n2. Unique elements in Array :\n");
Arrays.stream(uniqueArrays).forEach(System.out::println);
}
}
Output:
1. Original Array with duplicates :
Meta
Apple
Amazon
Netflix
Apple
Google
Netfilx
2. Unique elements in Array :
Meta
Apple
Amazon
Netflix
Google
Netfilx
Related Articles:
- Java 8 – How to find duplicate and its count in a Stream or List ?
- Java 8 – How to remove duplicates from ArrayList
- Java 8 – How to remove duplicates from LinkedList
- Java 8 – How to find duplicate and its count in an Arrays ?
- Java 8 – How to remove duplicate from Arrays ?
- Java 8 – Various ways to remove duplicate elements from Arrays
- Java 8 – How to remove an entry from HashMap by comparing keys
- Java 8 – How to remove an entry from HashMap by comparing values
References :
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct–
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEach-java.util.function.Consumer-
- https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#stream-T:A-
Happy Coding !!
Happy Learning !!