簡體   English   中英

如何使用java語言將解析字符串解析為hashmap

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

我有一個字符串但無法將其解析為Map

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

我需要從上面的字符串創建一個HashMap sakib hasan,sumon ali,tutul,shila akter應該是HashMap KEY和3,4,100,1,應該是KEYVALUE

我試過流動的代碼,但無法解決問題

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

如果沒有硬編碼,有沒有辦法可以做到這一點

試試這個。 您對“:”的拆分將單獨返回每個項目。

然后你只需要將每個組作為一組兩個,你可以在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]));
}

在你的代碼中,你的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()));

以下是使用流而不是for循環的類似解決方案:

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

或者您可以將.forEach轉換為創建地圖的收集器。

至少,我得到了答案

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