1


How to remove duplicate elements in an array using HashMap without using hashset in java...

Below code describes removal of duplicates in array..

Now i need to write using hashmap for generating key and value pairs

import java.util.*;

class TestArray{

public static void main(String arg[])
{

ArrayList<String> wordDulicate = new ArrayList<String>();

    wordDulicate.add("chennai");
    wordDulicate.add("bangalore");
    wordDulicate.add("hyderabad");
    wordDulicate.add("delhi");
    wordDulicate.add("bangalore");
    wordDulicate.add("mumbai");
    wordDulicate.add("mumbai");
    wordDulicate.add("goa");
    wordDulicate.add("calcutta");
    wordDulicate.add("hyderabad");

    ArrayList<String> nonDupList = new ArrayList<String>();

    Iterator<String> dupIter = wordDulicate.iterator();
    while(dupIter.hasNext())
    {
    String dupWord = dupIter.next();
    if(nonDupList.contains(dupWord))
    {
        dupIter.remove();
    }else
    {
        nonDupList.add(dupWord);
    }
    }
  System.out.println(nonDupList);
}
  }

2
  • A simpler way to to what you did is to do new ArrayList<String>(wordDuplicate). What values do you want to store? Commented Oct 19, 2012 at 10:18
  • I need to store as a key/value pair using HashMap... Commented Oct 19, 2012 at 12:46

3 Answers 3

3

A HashSet is implemented in terms of a HashMap anyway. If you specifically want to use a HashMap, use it the same way as HashSet does: use a dummy constant new Object() as the map value everywhere.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't get your comment. My answer explains what to do without using HashSet. It is almost exactly the same advice as in the answer you accepted.
0

Well a HashMap will prevent you from entering duplicate keys, the same way as HashSet. Actually, many implementations of HashSet just use a HashMap under the hood.

So you can do:

HashMap<String, String> map = new HashMap<String, String>();
for (String s : WordDuplicate) 
  map.put( s, s );

Now you can access the key/values just like a HashMap.

Comments

0
import java.util.HashSet;
import java.util.Stack;

public class stackdupes {

    public static void main(String[] args) {
        Stack<Integer> st = new Stack<Integer>();
        int[] arr= {1,2,3,3,4,5,5,7};
        HashSet<Integer> set = new HashSet<Integer>();

        for (int i=0;i<arr.length;i++) {
            if(set.add(arr[i]) == true)
            st.push(arr[i]);
        }
        System.out.println(st); 

    }   
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.