How to parse into hashmap using java language
I have a string but cannot parse it into a Map
string s="sakib hasan : 3 : sumon ali : 4 : tutul : 100
I need to create a line HashMap
on top. sakib hasan,sumon ali,tutul,shila akter
must be a KEY HashMap
and 3,4,100,1,
must be VALUE
from KEY
s.
I tried with the current code but couldn't 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 to do this without hardcoding
source to share
Try it. Your split on ":" will return each item individually.
Then you just need 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]));
}
source to share
In your code, the for loop goes through each item you split and each time adding only a hashmap only index 0 and 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()));
source to share