?
Solved

Remove duplicate values in HashMap and print the HashMap

Posted on 2011-02-15
14
Medium Priority
?
2,777 Views
Last Modified: 2012-05-11
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

0
Comment
Question by:puffyy_beginner
  • 6
  • 3
  • 2
  • +3
14 Comments
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 34900636


So what you mean by duplicate elements 2,2 and 2,2  or
also 2,1 and 2,2 ?

You don't want to have duplicate keys?
1
 

Author Comment

by:puffyy_beginner
ID: 34900734
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)
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34900771
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?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 5

Expert Comment

by:aciuica
ID: 34900859
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.
0
 

Author Comment

by:puffyy_beginner
ID: 34900890
Which data structure to u suggest for this kind of requirement? I want to have Integers tuples
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34900901

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);


}
 
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34900959
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
 

0
 
LVL 5

Expert Comment

by:aciuica
ID: 34900978
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

0
 

Author Comment

by:puffyy_beginner
ID: 34901162
Isn't there a simpler way to store tuples of Integers?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34901196
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
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34901212
You probably need a Set<T> where T holds a key/value pair. Override T.equals based on the key AND the value
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34901227
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
0
 
LVL 92

Expert Comment

by:objects
ID: 34901441
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>>
0
 
LVL 4

Expert Comment

by:msk_apk
ID: 34903516
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));
      }
}
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month17 days, 11 hours left to enroll

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question