英文:
How can i replace List<map> map key's value in java
问题
我想要替换这里所有迭代的时间值
List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
Map myMap1 = new HashMap();
myMap1.put("name", "jai");
myMap1.put("time", Instant.now());
mapList.add(myMap1);
Map myMap2 = new HashMap();
myMap2.put("name", "kishan");
myMap2.put("time", Instant.now());
英文:
I want to repalce here time value for all iteration
List<Map<String,Object>> mapList=new ArrayList<Map<String,Object>>();
Map myMap1=new HashMap();
myMap1.put("name", "jai");
myMap1.put("time", Instant.now());
mapList.add(myMap1);
Map myMap2=new HashMap();
myMap2.put("name", "kishan");
myMap2.put("time", Instant.now());
答案1
得分: 1
使用remove("time")
来返回旧值并放到新键中
mapList.forEach(map ->{
map.put("new time", map.remove("time"));
});
英文:
use remove("time")
to return old value and put to new key
mapList.forEach(map ->{
map.put("new time",map.remove("time"));
});
答案2
得分: 1
我得到了答案
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HelloWorld {
public static void main(String... args) {
List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
Map<String, Object> myMap1 = new HashMap<String, Object>();
myMap1.put("name", "jai");
myMap1.put("time", Instant.now());
mapList.add(myMap1);
Map<String, Object> myMap2 = new HashMap<String, Object>();
myMap2.put("name", "kishan");
myMap2.put("time", Instant.now());
mapList.add(myMap2);
System.out.println(mapList);
mapList.forEach(oneMap -> replaceKeyBy(oneMap));
System.out.println(mapList);
}
private static void replaceKeyBy(Map<String, Object> map) {
map.replace("time", Instant.now().plus(10, ChronoUnit.DAYS));
}
}
英文:
I got the answer
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HelloWorld {
public static void main(String... args) {
List<Map<String,Object>> mapList=new ArrayList<Map<String,Object>>();
Map<String, Object> myMap1=new HashMap<String, Object>();
myMap1.put("name", "jai");
myMap1.put("time", Instant.now());
mapList.add(myMap1);
Map<String, Object> myMap2=new HashMap<String, Object>();
myMap2.put("name", "kishan");
myMap2.put("time", Instant.now());
mapList.add(myMap2);
System.out.println(mapList);
mapList.forEach(oneMap -> replaceKeyBy(oneMap));
System.out.println(mapList);
}
private static void replaceKeyBy(Map<String, Object> map) {
map.replace("time",Instant.now().plus(10, ChronoUnit.DAYS));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论