googleart
asked on
String of values to Hash Map
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
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
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>();
BufferedReader br = new BufferedReader(new StringReader(s400));
String buff;
while((buff=br.readLine()) != null){
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}
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>();
BufferedReader br = new BufferedReader(new StringReader(s400));
String buff;
while((buff=br.readLine()) != null){
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}
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
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>();
BufferedReader br = new BufferedReader(new StringReader(s400));
String buff;
while((buff=br.readLine()) != null){
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(totalCo unt);
// }
// System.out.println(totalCo unt);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
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>();
BufferedReader br = new BufferedReader(new StringReader(s400));
String buff;
while((buff=br.readLine())
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(totalCo
// }
// System.out.println(totalCo
}catch(Exception ex){
ex.printStackTrace();
}
}
}
ASKER
Hi yan ,
I got some issue in this method implementation in my application,In some scenarios i am getting string as follows
EventDescription,EventCoun t
ACH Confirmation Notification ,0
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,EventCoun t
so i can put them in map and sum the values.
I got some issue in this method implementation in my application,In some scenarios i am getting string as follows
EventDescription,EventCoun
ACH Confirmation Notification ,0
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,EventCoun
so i can put them in map and sum the values.
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]));
}
ASKER
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>();
BufferedReader br = new BufferedReader(new StringReader(content));
String buff;
while((buff=br.readLine()) != null){
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],n ew Integer(ss[1]));
}
for(String value: map.keySet()){
Count = Count + map.get(value);
}
LoggerUtil.getInstance().d ebug(this. getClass() , "The count is :" + Count);
}catch(Exception ex){
ex.printStackTrace();
}
return Count;
}
the error in console
java.lang.NumberFormatExce ption: For input string: "EventCount"
at java.lang.NumberFormatExce ption.forI nputString (NumberFor matExcepti on.java:48 )
at java.lang.Integer.parseInt (Integer.j ava:447)
at java.lang.Integer.<init>(I nteger.jav a:620)
at com.wellsfargo.ws.ceo.smu. ew.dao.EwD ao.getCoun t(EwDao.ja va:433)
at com.wellsfargo.ws.ceo.smu. ew.service .EwService .getCount( EwService. java:105)
at com.wellsfargo.ws.ceo.smu. batch.hand ler.ProdSt atusJobHan dlerImpl.p rocessJob( ProdStatus JobHandler Impl.java: 63)
at com.wellsfargo.ws.ceo.smu. ejb.BatchE ventProces singMDBean .onMessage (BatchEven tProcessin gMDBean.ja va:60)
at weblogic.ejb.container.int ernal.MDLi stener.exe cute(MDLis tener.java :466)
at weblogic.ejb.container.int ernal.MDLi stener.tra nsactional OnMessage( MDListener .java:371)
at weblogic.ejb.container.int ernal.MDLi stener.onM essage(MDL istener.ja va:327)
at weblogic.jms.client.JMSSes sion.onMes sage(JMSSe ssion.java :4123)
at weblogic.jms.client.JMSSes sion.execu te(JMSSess ion.java:4 013)
at weblogic.jms.client.JMSSes sion$UseFo rRunnable. run(JMSSes sion.java: 4541)
at weblogic.work.SelfTuningWo rkManagerI mpl$WorkAd apterImpl. run(SelfTu ningWorkMa nagerImpl. java:464)
at weblogic.work.ExecuteThrea d.execute( ExecuteThr ead.java:2 00)
at weblogic.work.ExecuteThrea d.run(Exec uteThread. java:172)
coming in this line
try{
new Integer(ss[1]);
}catch(Exception ex1
can u suggest me whot ic causing this error in code?
my dao code is as folllows:
public int getCount(String content) {
int Count = 0;
try{
HashMap <String,Integer> map = new HashMap<String,Integer>();
BufferedReader br = new BufferedReader(new StringReader(content));
String buff;
while((buff=br.readLine())
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],n
}
for(String value: map.keySet()){
Count = Count + map.get(value);
}
LoggerUtil.getInstance().d
}catch(Exception ex){
ex.printStackTrace();
}
return Count;
}
the error in console
java.lang.NumberFormatExce
at java.lang.NumberFormatExce
at java.lang.Integer.parseInt
at java.lang.Integer.<init>(I
at com.wellsfargo.ws.ceo.smu.
at com.wellsfargo.ws.ceo.smu.
at com.wellsfargo.ws.ceo.smu.
at com.wellsfargo.ws.ceo.smu.
at weblogic.ejb.container.int
at weblogic.ejb.container.int
at weblogic.ejb.container.int
at weblogic.jms.client.JMSSes
at weblogic.jms.client.JMSSes
at weblogic.jms.client.JMSSes
at weblogic.work.SelfTuningWo
at weblogic.work.ExecuteThrea
at weblogic.work.ExecuteThrea
coming in this line
try{
new Integer(ss[1]);
}catch(Exception ex1
can u suggest me whot ic causing this error in code?
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
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
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
integer - so not printStacktrace is bnecessary
ASKER
Thank u yan for the help.
ASKER
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();
BufferedReader br = new BufferedReader(new StringReader(content));
String buff;
boolean isFirstLine = true;
while((buff=br.readLine()) != null){
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?
I got situation where i have same keys and different values so i tried in this way
Multimap<String, Integer> params = HashMultimap.create();
BufferedReader br = new BufferedReader(new StringReader(content));
String buff;
boolean isFirstLine = true;
while((buff=br.readLine())
if (isFirstLine) {
isFirstLine = false;
continue;
}
String [] totalEvents = buff.split(",");
params.put(totalEvents[0],
}
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?
Yes, that's waht they say in the API:
http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/HashMultimap.html
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>>
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.
ASKER
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
This is the code:
(You can make it a few lines shorter, but this way it is the easiest to see the logic):
(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>>();
BufferedReader br = new BufferedReader(new StringReader(content));
String buff;
boolean isFirstLine = true;
while((buff=br.readLine()) != null){
if (isFirstLine) {
isFirstLine = false;
continue;
}
String [] totalEvents = buff.split(",");
if(params.get(totalEvents[0]) == null){
ArrayList<Integer> ar = new ArrayList<Integer>();
ar.add(new Integer(totalEvents[1]));
params.put(totalEvents[0],ar);
} else {
ArrayList<Integer> ar = params.get(totalEvents[0]);
ar.add(new Integer(totalEvents[1]));
params.put(totalEvents[0],ar);
}
}
ASKER
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();
BufferedReader br = new BufferedReader(new StringReader(content));
String buff;
boolean isFirstLine = true;
while((buff=br.readLine()) != null){
if (isFirstLine) {
isFirstLine = false;
continue;
}
String [] totalEvents = buff.split(",");
mm.put(totalEvents[0],new Integer(totalEvents[1]));
Count= mm.totalSize();
MultiValueMap mm = new MultiValueMap();
BufferedReader br = new BufferedReader(new StringReader(content));
String buff;
boolean isFirstLine = true;
while((buff=br.readLine())
if (isFirstLine) {
isFirstLine = false;
continue;
}
String [] totalEvents = buff.split(",");
mm.put(totalEvents[0],new Integer(totalEvents[1]));
Count= mm.totalSize();
int count = 0;
MultiValueMap mm = new MultiValueMap();
BufferedReader br = new BufferedReader(new StringReader(content));
String buff;
boolean isFirstLine = true;
while((buff=br.readLine()) != null){
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
ASKER
Got it.Thank you very much for the help!!
You are always welcome.
Open in new window