3

I have a string but cannot parse it into Map

string s="sakib hasan : 3 : sumon ali : 4 : tutul : 100

I need to create a HashMap from above string. sakib hasan,sumon ali,tutul,shila akter should be KEY of HashMap and 3,4,100,1, should be VALUEs of KEYs.

I have tried with the flowing code but unable to solve the problem

Map<String, Integer>amap=new HashMap<String,Integer>(); 
String[] splt=s.split(":");
for (String string : splt)  
{ 
  String[] pair=string.split(" ");
  amap.put(pair[0])+Integer.parseInt(pair[1]);  
}

Is there a way can I do this without hard coding

1
  • Try using your debugger and stepping through the code. You will be able to see the value of string in each iteration and it should help you solve this problem, as well as other problems you may encounter in the future. Commented Jan 8, 2015 at 20:09

4 Answers 4

6

Try this. Your split on ":" will return each item individually.

Then you just have to take each group as a set of two which you can account for in the for loop with i+=2

Map < String, Integer > amap = new HashMap < String, Integer > ();
String[] splt = s.split(" : ");
for (int i = 0; i < splt.length; i += 2) {
    amap.put(splt[i],Integer.parseInt(splt[i + 1]));
}
Sign up to request clarification or add additional context in comments.

9 Comments

I completely failed with those compilation errors heh. Everything should be fixed now
Would the Integer you're putting into the map have to be trimmed of white space for parsing?
As Drew mentioned, I would add .trim() to the split[] and splt[] values
Thank you for mentioning that @DrewKennedy I fixed it in the answer
Should compile now with no issues. An alternative would be to split at ` : ` (pad the colon). :)
|
0

In your code, your for loop is going through each element that you split and every single time, adding the hashmap only index 0 & 1. You need to increment the indices.

    String s = "sakib hasan : 3 : sumon ali : 4 : tutul : 100 : shila akter : 1";

    Map<String, Integer> amap = new HashMap<String, Integer>();
    String[] splt = s.split(":");
    for(int i = 1; i < splt.length;i+=2)
        amap.put(splt[i-1].trim(), Integer.parseInt(splt[i].trim()));

3 Comments

Done this way, starting at 1, this will ensure that the put method will never be called on the last oddball element if it's an odd number of element for some reason. Also splitting at just the colon & trimming later ensures that if your string has a delimiter of "_:" or something like that instead of ":", it won't trip up on this.
I have a query to yours if it is two or more line string which i read from file then what will happen.such as string storage in file one line --> sakib hasan : 3 : sumon ali : 4 : tutul :,secondline..> 100 : shila akter : 1
That's going to be an issue in either implementation here, You're going to have to either concatenate the string before hand, or once the next line is read in call an intermediate put on the one in between. If you're reading from a file though, something like a Scanner will probably work a lot better.
0

Here is a similar solution using streams instead of a for loop:

IntStream.range(0, splt.length / 2)
    .forEach(i -> map.put(splt[i], Integer.parseInt(splt[i + 1]));

Or you could turn the .forEach into a collector that creates the map.

Comments

0

At least,I got the answer

Map<String, Integer>amap=new HashMap<String,Integer>(); 
String[] splt=s.split(":");
try {
    for (int i = 0; i <= pair.length; i +=2) {
    amap.put(pair[i].trim(), Integer.parseInt(pair[(1 + i)].trim()));
}
} catch (Exception e) {

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.