Solved

Remove duplicate values in HashMap and print the HashMap

Posted on 2011-02-15
14
2,248 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
[X]
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
  • 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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
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

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This video teaches viewers about errors in exception handling.

705 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