Remove Duplicates from array in Java using collection
In this tutorial, we will learn how to remove duplicates from an array in Java using collection.
we will use list interface in java. It is a child interface of collection. It is an ordered collection of an object in which duplicate values can be stored.
List interface is implemented by
- Array list
- Linked list
- Vector
- Stack classes
What is a collection in java?
A collection represents a single unit of objects.
e.g: Group.
Remove Duplicates from an array in java using collection
- First, the program will iterate through original arrays to read duplicate elements
- Then it will convert arrays into a list using the array’s asList(arrObj) method
- Then it will add the converted list into HashSet using inter-conversion collection constructor to remove duplicates
- Next, it will create new arrays of required data-type
- Now it will convert set to arrays
- Next, it will again iterate through HashSet to print unique elements
Remove Duplicate Elements From Unsorted Array And Print Sorted in Java
Input:
Array={ "zeyan","kingson","saurabh","dennis","rudrankash","zeyan","saurabh" }
package in.bench.resources.java.arrays; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class RemoveDuplicateUsingListAndSet { // main() method - entry point for JVM public static void main(String[] args) { // initialize an Arrays with duplicate values String[] strArray = {"zeyan","kingson","saurabh","dennis","rudrankash","zeyan","saurabh"}; // invoke removeDuplicatesFromArray() with above initialized Arrays removeDuplicatesFromArray(strArray); } /** * This method removes duplicate elements from Arrays * using List and Set classes and finally prints unique elements * @param strArray */ public static void removeDuplicatesFromArray(String[] strArray) { // Iterating using enhanced for-loop System.out.println("Original Arrays with duplicates:\n"); for(String str : strArray) { System.out.println(str); } // convert Arrays into List List<String> lst = Arrays.asList(strArray); // again convert List into Set, for removing duplicates // using inter-conversion constructor Set<String> set = new HashSet<String>(lst); // create new String[] with no. of elements inside Set String[] uniqueArr = new String[set.size()]; // convert back Set into Arrays set.toArray(uniqueArr); // Iterating using enhanced for-loop System.out.println("\n\nUnique elements:\n"); for(String uStr : uniqueArr) { System.out.println(uStr); } } }
Output:
Original Arrays with duplicate : { "zeyan","kingson","saurabh","dennis","rudrankash","zeyan","saurabh" } Unique elements: { "zeyan","kingson","saurabh","dennis","rudrankash" }
Also read:
Leave a Reply