Link to home
Start Free TrialLog in
Avatar of puffyy_beginner
puffyy_beginner

asked on

Remove duplicate values in HashMap and print the HashMap

hello experts,
I have the followng code and i am looking of additional code on ho I will remove the duplicate elements of the hashMap and the how to print it.
Map<Integer,Integer> myArr=new HashMap<Integer, Integer>();
		
		myArr.put(2,1);
		myArr.put(2,1);
		myArr.put(2,2);
		myArr.put(2,2);
		myArr.put(3,1);
		myArr.put(3,1);
		myArr.put(4,1);
		myArr.put(4,1);
		myArr.put(2,1);
		myArr.put(2,1);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of puffyy_beginner
puffyy_beginner

ASKER

I want to have duplicate keys but not both key,value duplications. So I want the output to be (2,1) (2,2)(3,1)(4,1)
So how are you going to retrive values later from your HasMap?
if I give you key 2 - you want to get back the list of 1,2,etc?
In HashMap you cannot have duplicate keys.
If you write System.out.println(myArr) after your code you will have: {2=1, 3=1, 4=1}
Probably you need a little bit different structure.
Better to say the main problem like for_yan try to ask you and some of us maybe can advise.
Which data structure to u suggest for this kind of requirement? I want to have Integers tuples

As uou cannot have two avlues associated with one key,
whenthere is such need I store vector or arraylist associated with the key.

In this way your HashMap will have
vector (or ArrayList) of values associated with each key
The code may be like that:


ArrayList firstNumbers;
ArrayList secondNumbers; - let's believe these are fillled with your  initial numbers

HashMap m = new HashMap();
ArrayList checkList = new ArrayList();

for(int j=0; j<firstNumbers.size(); j++){
Integer i1 = (Integer) firstNumbers(j);
Integer i2 = (Integer)secondNumbers(j);
String s = i1.toString() + "," + i2.toString();
if(checkList.contains(s))continue;

if(m.get(i1) != null){
ArrayList a1 = (ArrayList)m.get(i1);
a1.add(i2);
}
else
{
ArrayList a1 = new ArrayList();
a1.add(i2);
}
m.put(i1,i2);
}
checkList.add(s);


}
 
In order to print you do something like the following:

Enumeration keys = m.keys();
while(keys.hasMoreElements()){
Integer i1 = (Integer) keys.nextElement();
ArrayList a = (ArrayList)m.get(i1);
System.out.println(i1.toString());
for(int j=0; j<a.size(); j++)System.out.println("  " + ((Integer)a.get(j)).toString());
}

Maybe just m.toString() can also print something useful, but
maybe this is too complex structure to get a decent toString() from it
 

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class HashTest {

	public static void main(String[] args) {
		MyMap myArr = new MyMap();

		myArr.put(2, 1);
		myArr.put(2, 1);
		myArr.put(2, 2);
		myArr.put(2, 2);
		myArr.put(3, 1);
		myArr.put(3, 1);
		myArr.put(4, 1);
		myArr.put(4, 1);
		myArr.put(2, 1);
		myArr.put(2, 1);
		
		System.out.println(myArr);
	}
	
}
class MyMap extends HashMap<Integer, List<Integer>> {
	public void put(Integer key, Integer value) {
		if (containsKey(key)) {
			List<Integer> list = get(key);
			if (!list.contains(value)) {
				list.add(value);
			}
		} else {
			List<Integer> list = new ArrayList<Integer>();
			list.add(value);
			put(key, list);
		}
	}
}

Open in new window

Isn't there a simpler way to store tuples of Integers?
It is better to have arraylist of say strings "1,2"
Or you can make your own class Tuple and
make arraylits  out of it
Avatar of CEHJ
You probably need a Set<T> where T holds a key/value pair. Override T.equals based on the key AND the value
The purpose of hashtable or hashmap is actually to retrieve very quickly something
corresponding to a key. If you have really a lot of data - you
can store strings, like "1,2", "1,3", etc, in the arraylist and then check
each one string and slect those which have first integer on1, but it will be much slower than
if youy store it in Hasmap.
If you have afew dozen - doesnot matter.
If it comes to millions - this matters
for dozens - storing strings with seprator , say comma, would be the fastetst
use the following for storing your pairs

http://stackoverflow.com/questions/521171/a-java-collection-of-value-pairs-tuples

you'd then use

Set<Pair<Integer, Integer>>
import java.util.*;
public class IntegerPair {

      private int firstInt = 0;
      private int secondInt = 0;
      
      public IntegerPair(int firstInt, int secondInt)
      {
            this.firstInt = firstInt;
            this.secondInt = secondInt;
      }
      
      public int hashCode()
      {
            return Integer.parseInt(firstInt+""+secondInt);
      }
      
      public int getFirstInt()
      {
            return this.firstInt;
      }
      
      public int getSecondInt()
      {
            return this.secondInt;
      }
      
      public boolean equals(Object obj)
      {
            if(!(obj instanceof IntegerPair))
            {
                  return false;
            }
            
            IntegerPair temp = (IntegerPair)obj;
            
            if(this.firstInt == (temp.getFirstInt()) && this.secondInt == (temp.getSecondInt()))
            {
                  return true;
            }
            
            return false;
      }
      
      public static void main(String a[])
      {
            HashMap map = new HashMap();
            IntegerPair one = new IntegerPair(1,2);
            IntegerPair two = new IntegerPair(2,2);
            System.out.println("one =="+one.hashCode());
            System.out.println(" second =="+two.hashCode());
            System.out.println(" equals =="+one.equals(two));
      }
}