Link to home
Start Free TrialLog in
Avatar of googleart
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
Avatar of for_yan
for_yan
Flag of United States of America image

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

BuffereReader br = new BufferedReader(new StringReader(s));
String buff;
while((buff=br.readLine()) != null){
String [] ss = s.split(",");
map.put(ss[0],ss[1]);

}

Open in new window




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();
      }
}

Open in new window

Outpurt:
{A=1, B=2, C=3}

Open in new window

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();
      }
}
}

Open in new window


{A=1, B=2, C=3}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of googleart
googleart

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(totalCount);
//      }    
//                System.out.println(totalCount);
      
            }catch(Exception ex){
                ex.printStackTrace();
            }
      }
}
Hi yan ,
I got some issue in this method implementation in my application,In some scenarios i am getting  string as follows
EventDescription,EventCount
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,EventCount
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]));
   
      }

Open in new window

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],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)
      at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:464)
      at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)
      at weblogic.work.ExecuteThread.run(ExecuteThread.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?
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
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
Thank u yan for the help.
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?

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>> 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.





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):

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);
}
                           
                        
                  }

Open in new window

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();
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]);
}

Open in new window


after the process finishes you'll have the sum in the
count
varaible
Got it.Thank you very much for the help!!
You are always welcome.