Java 8 – How to remove duplicate from Arrays ?

In this article, we will discuss how to remove duplicate elements from Array

Also read,

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

References :

Happy Coding !!
Happy Learning !!

Java 8 - How to find duplicate in a Stream or List
Java 8 - Convert Stream to ConcurrentHashMap