Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Remove duplicate values in HashMap and print the HashMap

Posted on 2011-02-15
14
2,031 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 500 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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
web services creation SOAP vs REST 5 56
reverse digits of a number using for loop 5 52
servlet example issue 6 46
Tagging and Merging on Branch 1 29
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

809 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