We help IT Professionals succeed at work.

# String of values to Hash Map

on
Medium Priority
488 Views
I have a situation where i need to convert string of values to hash map.for example i have string of values as follows
A,1
B,2
C,3
and so on.I need to convert and put in to hash map as key and value.Confused how to do it.Can someone help me in this?Thank u
Comment
Watch Question

## View Solution Only

Awarded 2011
Awarded 2011

Commented:
I think something like that should work:
``````HashMap <String,String> map = newe HashMap<String,String>();

String buff;
String [] ss = s.split(",");
map.put(ss[0],ss[1]);

}
``````

Awarded 2011
Awarded 2011

Commented:
``````public class MakeHashMap {
public static void main(String[] args) {
try{
String s400 = "A,1\nB,2\nC,3\n";

HashMap <String,String> map400 = new HashMap<String,String>();

String buff;
String [] ss = buff.split(",");
map400.put(ss[0],ss[1]);

}

System.out.println(map400);

}catch(Exception ex){
ex.printStackTrace();
}
}
``````
Outpurt:
``````{A=1, B=2, C=3}
``````
Awarded 2011
Awarded 2011

Commented:
This is the same thing, but if you want HashMap<String, Integer> rather than <String, String>
``````public class MakeHshMap {
public static void main(String[] args) {
try{
String s400 = "A,1\nB,2\nC,3\n";

HashMap <String,Integer> map400 = new HashMap<String,Integer>();

String buff;
String [] ss = buff.split(",");
map400.put(ss[0],new Integer(ss[1]));

}

System.out.println(map400);

}catch(Exception ex){
ex.printStackTrace();
}
}
}
``````

``````{A=1, B=2, C=3}
``````
Awarded 2011
Awarded 2011
Commented:
The same thing with a little bit more obvious output:

``````public class MakeHashMap {
public static void main(String[] args) {
try{
String s400 = "A,1\nB,2\nC,3\n";

HashMap <String,Integer> map400 = new HashMap<String,Integer>();

String buff;
String [] ss = buff.split(",");
map400.put(ss[0],new Integer(ss[1]));

}

for(String s401: map400.keySet()){
System.out.println("key: " + s401 + " value: " + map400.get(s401));
}

}catch(Exception ex){
ex.printStackTrace();
}

}
}
``````

Output:
``````key: A value: 1
key: B value: 2
key: C value: 3
``````

Commented:
Thank You i got it done.This what i am tryingto add sum the values.

public class Test {
public static void main(String[] args) {
int totalCount=0;
try{
String s400 = "A,1\nB,2\nC,3\n";

HashMap <String,Integer> map400 = new HashMap<String,Integer>();
HashMap <String,Integer> map2 = new HashMap<String,Integer>();

String buff;
String [] ss = buff.split(",");
map400.put(ss[0],new Integer(ss[1]));
map2.putAll(map400);
}
for(String s401: map400.keySet()){
totalCount = totalCount +  map400.get(s401);
System.out.println("key: " + s401 + " value: " + map400.get(s401));
}
//      System.out.println("map is"+map2);
//      for (Integer value : map2.values()) {
//            totalCount = totalCount + value;
//      }
System.out.println("Count is"+totalCount);
//      }
//      int totalCount=0;
//      for (Integer value : map2.values()) {
//            totalCount = totalCount + value;
//            System.out.println(totalCount);
//      }
//                System.out.println(totalCount);

}catch(Exception ex){
ex.printStackTrace();
}
}
}

Commented:
Hi yan ,
I got some issue in this method implementation in my application,In some scenarios i am getting  string as follows
EventDescription,EventCount
Unauthorized ACH Transactions,0
ARP File Confirmation,0
File Receipt Confirmation,0
Communication Center Weekly Digest,0
CEO Portal User ID has been Disabled,6
CEO Portal User ID has been Re-enabled,8

can you suggest how to remove the first line from the string i.e EventDescription,EventCount
so i can put them in map and sum the values.
Awarded 2011
Awarded 2011

Commented:
yes, you can do like that:

`````` while((buff=br.readLine()) != null){
String [] ss = buff.split(",");
boolean goodInt = true;
try{
new Integer(ss[1]);
}catch{
goodInt = false;
}
if(goodInt)map400.put(ss[0],new Integer(ss[1]));

}
``````

Commented:
Thank u yan i got the sum done and the good working but iam getting numberformat error in console
my dao code is as folllows:
public int getCount(String content) {
int Count = 0;
try{
HashMap <String,Integer> map = new HashMap<String,Integer>();
String buff;
String [] ss = buff.split(",");
boolean goodInt = true;
try{
new Integer(ss[1]);
}catch(Exception ex1){
ex1.printStackTrace();
goodInt = false;
}
if(goodInt)map.put(ss[0],new Integer(ss[1]));
}
for(String value: map.keySet()){
Count = Count +  map.get(value);
}
LoggerUtil.getInstance().debug(this.getClass(), "The count  is :" + Count);
}catch(Exception ex){
ex.printStackTrace();
}
return Count;
}

the error in console
java.lang.NumberFormatException: For input string: "EventCount"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.<init>(Integer.java:620)
at com.wellsfargo.ws.ceo.smu.ew.dao.EwDao.getCount(EwDao.java:433)
at com.wellsfargo.ws.ceo.smu.ew.service.EwService.getCount(EwService.java:105)
at com.wellsfargo.ws.ceo.smu.batch.handler.ProdStatusJobHandlerImpl.processJob(ProdStatusJobHandlerImpl.java:63)
at com.wellsfargo.ws.ceo.smu.ejb.BatchEventProcessingMDBean.onMessage(BatchEventProcessingMDBean.java:60)
at weblogic.ejb.container.internal.MDListener.execute(MDListener.java:466)
at weblogic.ejb.container.internal.MDListener.transactionalOnMessage(MDListener.java:371)
at weblogic.ejb.container.internal.MDListener.onMessage(MDListener.java:327)
at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:4123)
at weblogic.jms.client.JMSSession.execute(JMSSession.java:4013)
at weblogic.jms.client.JMSSession\$UseForRunnable.run(JMSSession.java:4541)

coming in this line
try{
new Integer(ss[1]);
}catch(Exception ex1
can u suggest me whot ic causing  this error in code?
Awarded 2011
Awarded 2011

Commented:
remove
ex1.printStackTrace();
it just prints exactly bacuase I'm checjing - it should go forward and
you don't need tioo print it - I want to check for this exectipoon - and it will not add
it to the mao if this excepton is throwsn - this is probably the oly case where you don't wan to print stack trace because you simple expect it
Awarded 2011
Awarded 2011

Commented:
In this case I use chatching exceptio not to check for errors but just to determine if the item is fromatted as
integer - so not printStacktrace is bnecessary

Commented:
Thank u yan for the help.

Commented:
Hi yan ,
I got situation where i have same keys and different values so i tried in this way
Multimap<String, Integer> params = HashMultimap.create();
String buff;
boolean isFirstLine = true;
if (isFirstLine) {
isFirstLine = false;
continue;
}
String [] totalEvents = buff.split(",");
params.put(totalEvents[0],new Integer(totalEvents[1]));

}
for(Integer value: params.values()){
Count = Count +value;
}

it was working.but there was another case where same keys and same values like
{1,7
1,7}
it was taking only one value and ignoring another valuE.Wondering how to solve this,can you suggest a idea?
Awarded 2011
Awarded 2011

Commented:

Yes, that's waht they say in the API:

The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an existing key-value pair has no effect.

Check this one from Apache Commons - it does not look like it has sucvh limitation:
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/MultiValueMap.html

Frankly, when I encounter such situations I don't use these MultiMaps
but rather create my own

HashMap <String,Arraylist<String>> or maybe HashMap<Integer, ArrayList<String>> if nececssray.

It is easy to populate ssuch HashMap - you just check if this key already exist and either retrieve ArrayList and add one more value
or create a new ArrayList.
and you can always retrive ArrayList for each key
ArrayList can have duplicate values, so your situation should not be a problem.

Commented:
thank you i tried with multi value map not getting it work.can u provide code snippet how to do with arrylist and hash map
Awarded 2011
Awarded 2011

Commented:
This is the code:
(You can make it a few lines shorter, but this way it is the easiest to see the logic):

``````HashMap<String, ArrayList<Integer>> params = new HashMap<String, ArrayList<Integer>>();

String buff;
boolean isFirstLine = true;
if (isFirstLine) {
isFirstLine = false;
continue;
}
String [] totalEvents = buff.split(",");
if(params.get(totalEvents[0]) == null){

ArrayList<Integer> ar = new ArrayList<Integer>();
params.put(totalEvents[0],ar);
}  else {
ArrayList<Integer> ar = params.get(totalEvents[0]);
params.put(totalEvents[0],ar);
}

}
``````

Commented:
thank you yan for snippet.i am trying with multivaluemap as follows i got the count correct and trying to sum the values ,but not getting it can you suggest how to sum from the multivaluemap?

MultiValueMap mm = new MultiValueMap();
String buff;
boolean isFirstLine = true;
if (isFirstLine) {
isFirstLine = false;
continue;
}
String [] totalEvents = buff.split(",");
mm.put(totalEvents[0],new Integer(totalEvents[1]));
Count= mm.totalSize();
Awarded 2011
Awarded 2011

Commented:
``````int count = 0;
MultiValueMap mm = new MultiValueMap();
String buff;
boolean isFirstLine = true;
if (isFirstLine) {
isFirstLine = false;
continue;
}
String [] totalEvents = buff.split(",");
mm.put(totalEvents[0],new Integer(totalEvents[1]));
count = count + Integer.parseInt(totalEvents[1]);
}
``````

after the process finishes you'll have the sum in the
count
varaible

Commented:
Got it.Thank you very much for the help!!
Awarded 2011
Awarded 2011

Commented:
You are always welcome.