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

+3


source to share


4 answers


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

}

      

0


source


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

      

+6


source


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

      

0


source


Here's 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 can include .forEach on the collector that creates the map.

0


source







All Articles