Solved

Remove duplicate values in HashMap and print the HashMap

Posted on 2011-02-15
14
1,779 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
Comment Utility


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
Comment Utility
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
Comment Utility
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
 
LVL 5

Expert Comment

by:aciuica
Comment Utility
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
Comment Utility
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
Comment Utility

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
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 5

Expert Comment

by:aciuica
Comment Utility
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
Comment Utility
Isn't there a simpler way to store tuples of Integers?
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

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 This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This video teaches viewers about errors in exception handling.
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.

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now