将Map键中的字符串替换为Map值中的字符串

时间:2017-06-26 09:52:55

标签: java hashmap

我有这段代码

import java.util.*;

public class Tester {
public static void main(String[] args) {

    HashMap<String, String> data=new HashMap();
    data.put("Chance to Avoid Fire Damage when Hit", "(3-7)%");
    data.put("Chance to Avoid Cold Damage when Hit", "(6-8)%");
    data.put("Chance to Avoid Chaos Damage when Hit", "(6-7)%");
    data.put("Adds # to # Fire Damage to Spells", "{\"min\":10,\"avg\":20,\"max\":30}");
    data.put("Adds # to # Cold Damage to Curses", "{\"avg\":20,\"max\":30,\"min\":10}");
    data.put("Adds # to # Cold Damage to Curses", "{\"avg\":30,\"max\":20,\"min\":40}");
    data.put("Adds # to # Physical Damage to Weapon", "{\"min\":8,\"max\":32,\"avg\":20}");
    data.put("Curse Enemies with Vulnerability on level", "30");

}
}

我们的老师要求我们制定一个方法来取代每个第一个&#34;#&#34;用他的最小值和第二个&#34;#&#34;具有最大值 例如:&#34;对法术增加10到30点火焰伤害......&#34; 我已经做错了几个小时,真的需要一些帮助 这就是我迄今为止所做的事情(我知道它可能很糟糕):

public class Exe2 {
public static String replaceH(Map<String, String> mods) {
    Set<String> modss = new HashSet();
    String z="";
    String[] keys = mods.keySet().toArray(new String[0]);
    String key = mods.get(keys);
    for (String n : keys) {
        if(n.contains("#")){
           z= n.replace("#",key.indexOf(5));

        }
    }
    return z;
}

}

非常感谢您的帮助,谢谢:)

5 个答案:

答案 0 :(得分:0)

您必须在循环中使用井号[{1}}删除旧密钥。 并插入带有替换值的键。

因为在循环中同时移除和插入可能会有问题,您可以使用新结果构建第二个地图,或者反过来,首先从原始地图复制(相关)键。

要从最小值和最大值中检索,可以使用正则表达式模式匹配:#或更难value.replaceFirst("...", "$1");

答案 1 :(得分:0)

首先,您应该在地图中使用重复的键,这样才能获得三个输出而不是四个输出。

其次,为了使问题更简单,你应该使用相同的模式:

package tests;
import java.util.*;
public class Tester {

    public static void main(String[] args) {
        getFinal(initial(data));

    }
public static Map<String,String> initial(Map<String,String>a){
          a.put("Chance to Avoid Fire Damage when Hit","(3-7)%");
          a.put("Chance to Avoid Cold Damage when Hit", "(6-8)%");
          a.put("Chance to Avoid Chaos Damage when Hit", "(6-7)%");
          a.put("Adds # to # Fire Damage to Spells", "{\"avg\":20,\"max\":30,\"min\":10}");
          a.put("Adds # to # Cold Damage to Curses", "{\"avg\":20,\"max\":30,\"min\":10}");
          a.put("Adds # to # Cold Damage to Curses", "{\"avg\":30,\"max\":20,\"min\":40}");
          a.put("Adds # to # Physical Damage to Weapon", "{\"avg\":20,\"max\":32,\"min\":8}");
          a.put("Curse Enemies with Vulnerability on level", "30");
          return a;
      }

 public static Map<String,String>getFinal(Map<String,String>b){
         List<String>aux=new ArrayList<String>(b.keySet());
         List<String>aux1=new ArrayList<String>(b.keySet());
         for(int i=0;i<b.size();i++){
             if(aux.get(i).contains("#")){
                 String min=b.get(aux.get(i)).split(",")[2];
                 String max=b.get(aux.get(i)).split(",")[1];
                 String minVal=min.split(":")[1].replace("}","").trim();
                 String maxVal=max.split(":")[1].trim();
                 String c=aux.get(i).replaceFirst("#",minVal);
                 String d=c.replaceAll("#",maxVal);
                 System.out.println(d);
                 b.replace(aux1.get(i),c);

             }
             }

             return b;
         }
}

输出:

Adds 40 to 20 Cold Damage to Curses
Adds 8 to 32 Physical Damage to Weapon
Adds 10 to 30 Fire Damage to Spells

答案 2 :(得分:0)

你可以试试这个

public class ChangeMapKeysWithValue {

    public static void main(String[] args) {

        HashMap<String, String> data=new HashMap<String, String>();
        HashMap<String, String> newData=new HashMap<String, String>();
        data.put("Chance to Avoid Fire Damage when Hit", "(3-7)%");
        data.put("Chance to Avoid Cold Damage when Hit", "(6-8)%");
        data.put("Chance to Avoid Chaos Damage when Hit", "(6-7)%");
        data.put("Adds # to # Fire Damage to Spells", "{\"min\":10,\"avg\":20,\"max\":30}");
        data.put("Adds # to # Cold Damage to Curses", "{\"avg\":20,\"max\":30,\"min\":10}");
        data.put("Adds # to # Cold Damage to Curses", "{\"avg\":30,\"max\":20,\"min\":40}");
        data.put("Adds # to # Physical Damage to Weapon", "{\"min\":8,\"max\":32,\"avg\":20}");
        data.put("Curse Enemies with Vulnerability on level", "30");

        Set<String> keySet = data.keySet();
        Iterator<String> itr = keySet.iterator();

        while(itr.hasNext()) {

            String key = itr.next();
            String value = data.get(key);

            if(key.contains("#")) {

                String[] valueArray = value.substring(1, value.length()-1).split(",");

                Map<String, String> valueSplitMap = new HashMap<String, String>();
                valueSplitMap.put(valueArray[0].split(":")[0], valueArray[0].split(":")[1]);
                valueSplitMap.put(valueArray[1].split(":")[0], valueArray[1].split(":")[1]);
                valueSplitMap.put(valueArray[2].split(":")[0], valueArray[2].split(":")[1]);

                key = key.replace("#", valueSplitMap.get("\"min\""));
                key = key.replace("to " + valueSplitMap.get("\"min\""), "to " + valueSplitMap.get("\"max\""));                          
            }
            if(key != null && !key.isEmpty()) {

                newData.put(key, value);
            }
        }

        System.out.println(newData);
    }
}

答案 3 :(得分:0)

通常你不会永远不会改变原始对象,所以可能是一个很好的实践,使用它就像一个只读对象并将结果放在一个新对象中,无论如何我的实现是使用json库 java-json。 jar ,您可以集成到您的项目中,也可以向您的教授展示。我相信他能够欣赏它。

代码下方(仅显示结果):

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;


public class Tester {

    public Tester() {
        // TODO Auto-generated constructor stub
    }

    public static String replaceAt(String s,int pos,String val) {
        return s.substring(0, pos) + val + s.substring(pos + 1);
      }

    public static void main(String[] args) throws JSONException {
        // TODO Auto-generated method stub

        HashMap<String, String> data=new HashMap();
        HashMap<String, String> result=new HashMap();
        data.put("Chance to Avoid Fire Damage when Hit", "(3-7)%");
        data.put("Chance to Avoid Cold Damage when Hit", "(6-8)%");
        data.put("Chance to Avoid Chaos Damage when Hit", "(6-7)%");
        data.put("Adds # to # Fire Damage to Spells", "{\"min\":10,\"avg\":20,\"max\":30}");
        data.put("Adds # to # Cold Damage to Curses", "{\"avg\":20,\"max\":30,\"min\":10}");
        data.put("Adds # to # Cold Damage to Curses", "{\"avg\":30,\"max\":20,\"min\":40}");
        data.put("Adds # to # Physical Damage to Weapon", "{\"min\":8,\"max\":32,\"avg\":20}");
        data.put("Curse Enemies with Vulnerability on level", "30");

        String[] keys = data.keySet().toArray(new String[0]);   
        for (String n : keys) {
            String value2 ="";
            String value ="";
            if(n.contains("#")){
                value = data.get(n);        
            JSONObject object = new JSONObject(value);
            String[] valuekeys = JSONObject.getNames(object);
            int cont =0;
            for (String key2 : valuekeys)
            {
                if("min".equals(key2)){
                     value2 =object.get(key2).toString();
                    int pos = n.indexOf("#");               
                     n=replaceAt(n, pos, value2);
                }
                 if("max".equals(key2)){
                      value2 =object.get(key2).toString();
                     int pos = n.lastIndexOf("#");           
                    n= replaceAt(n, pos, value2);
                } 

            }
             System.out.println(n); 

        }   
        }

    }
}

答案 4 :(得分:0)

通过使用 groovy:

Map<String, String> reference = [
    '1' : 'apple'  ,
    '2' : 'banana' ,
    '3' : 'pears'  ,
    '4' : 'peach'
]

'I want 1 she wants 4'.tokenize(' ')
                      .collect { references.get(it) ?: it }
                      .join(' ')

// result:
I want apple she wants peach

或者使用以下保持字符串格式

'I like    1, she    likes    3.'
    .replaceAll("[^\\w]", "_\$0")
    .split('_')
    .collect {
        String c = it.trim()
        reference.get(c) ? it.replace(c, reference.get(c)) : it
     }
    .join()

// Result: I like    apple, she    likes    pears.