» » Remove duplicates from an array java

Removing duplicate elements form an array using collections:

  1. package com.instanceofjavaTutorial;
  2.  
  3. import java.util.Arrays;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Set;
  7.  
  8. public class RemoveDupArray {
  9.  
  10.   public static void main(String[] args) {
  11.  
  12.   // A string array with duplicate values
  13.    String[] data = { "E", "C", "B", "E", "A", "B", "E", "D", "B", "A" };
  14.  
  15. System.out.println("Original array         : " + Arrays.toString(data));
  16.  
  17.  List<String> list = Arrays.asList(data);
  18.  Set<String> set = new HashSet<String>(list);
  19.  
  20.   System.out.print("After removing duplicates: ");
  21.   String[] resarray= new String[set.size()];
  22.    set.toArray(resarray);
  23.  
  24.  for (String ele: resarray) {
  25.  
  26.  System.out.print(ele + ", ");
  27.  
  28.  }
  29.  
  30. }
  31.  
  32. }



  1. OutPut:
  2. Original array         : [E, C, B, E, A, B, E, D, B, A]
  3. After removing duplicates: D, E, A, B, C




You Might Like:

1. Java Interview Programs On Core Java

2. Java Interview Programs On Collections 

3. What is The Output Of Following Programs Java Interview:

4. Java Concept and Example Program

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu