简体   繁体   English

如何使用java语言将解析字符串解析为hashmap

[英]How to string parse into hashmap using java language

I have a string but cannot parse it into Map 我有一个字符串但无法将其解析为Map

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

I need to create a HashMap from above string. 我需要从上面的字符串创建一个HashMap sakib hasan,sumon ali,tutul,shila akter should be KEY of HashMap and 3,4,100,1, should be VALUE s of KEY s. sakib hasan,sumon ali,tutul,shila akter应该是HashMap KEY和3,4,100,1,应该是KEYVALUE

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 如果没有硬编码,有没有办法可以做到这一点

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 然后你只需要将每个组作为一组两个,你可以在for循环中考虑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]));
}

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. 在你的代码中,你的for循环遍历你拆分的每个元素和每一次,只添加hashmap索引0和1.你需要增加索引。

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

Here is a similar solution using streams instead of a for loop: 以下是使用流而不是for循环的类似解决方案:

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. 或者您可以将.forEach转换为创建地图的收集器。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM