公司有一个需求,需要替换掉map中的value值,但是动态去替换。开始自己一直傻逼用的双重循环,结果导致map的值都被重复覆盖了,特此记录一下。
HashMap<String, String> map = new HashMap<String, String>();
map.put("A", "");
map.put("B", "");
map.put("C", "");
String[] strs = "123,456,789".split(",");
伪代码,去表示数据。其中map是动态的,而strs也是动态的集合或者数组。现在需要的是把这其中的map的key和strs集合中的值对应上。替换的结果如下。
{A=123, B=456, C=789}
实现方式,利用map的keySet,得到key的集合。利用下标然后再利用map去put进去。
方法一:
List<String> list = new ArrayList<>();
for (String s : map.keySet()) {
list.add(s);
}
for (int i = 0; i < list.size(); i++) {
if(strs.length > i){
map.put(setList.get(i),strs[i]);
}
}
System.out.println(map);
{A=123, B=456, C=789}
方法二:
int i = 0;
for (String key : map.keySet()) {
map.put(key, strs[i]);
i += 1;
}
System.out.println(map);
{A=123, B=456, C=789}