如何访问public Map<String, Object> getListInsideMapObject(Long id, Date from) {
Map<String, Object> result = new HashMap<>();
List<Map<String, Object>> mapList = new ArrayList<>();
List<MappedList> conTime = new ArrayList<>();
conTime = xxxRepository.findByxxx(id, from);
Map<String, Object> map = xxxService.xxx(id);
List<String> times = (List<String>) map.get("xxx");
for (MappedList t : conTime) {
int num = 0;
Map<String, Object> res = new HashMap<>();
res.put("x", "");
res.put("status", null);
for (Contraction c : con) {
num++;
res.put("status", "stat");
res.put("x", new Date());
}
}
res.put("y", num);
mapList.add(res);
result.put("mapList", mapList);
result.put("mapListA", mapListA);
result.put("mapListB", mapListB);
//etc
return result;
}
类型地图中的列表?
getListInsideMapObject
我正在尝试调用此服务(dangerouslySetInnerHTML
)并从此映射访问每个列表并遍历每个列表。例如在类xxx中我想调用getListInsideMapObject(Long id,Date from)作为服务并从地图访问每个列表
答案 0 :(得分:1)
我想你想要这样的东西:
public NewClass1() {
// have an instance from the class that gives you the map
ClassThatBuildsTheMap mapClass = new ClassThatBuildsTheMap();
// get the map. must provide id and date
Map <String, Object> myMap = mapClass.getListInsideMapObject(id, date);
// access the lists inside the map
useListInsideAMap(myMap);
}
private void useListInsideAMap(Map<String, Object> map){
// Prior to Java8:
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey(); // if you want to use the key
Object value = entry.getValue();
if(value instanceof List){
// I supose it is a list of sytrings
List l = (List) value;
for (Object item : l) {
// Do something with the item from the list
}
}
}
// Java8:
// loop through the map
map.forEach((String key, Object value)->{
// if you want to use key, just call key
// checks if the value (Object) from the map is a list
if(value instanceof List){
List l = (List)value;
// loop through the list
l.forEach((Object item)->{
// Do something with the item from the list
});
}
});
}
答案 1 :(得分:0)
您可以将Object
转换为List
Map<String, Object> result = new HashMap<>();
List<Map<String, Object>> mapList= new ArrayList<>();
result.put("1", mapList);
-------------------------------------------------------
List<Map<String, Object>> = (List<Map<String, Object>>)result.get("1")
然后,您可以使用for / foreach正常循环。
答案 2 :(得分:0)
此外,您可以使用Optional
对象按键获取地图值,并在转换为所需类型之前检查它(以避免ClassCastException
问题):
Map<String, Object> someMap = new HashMap<>();
List<Map<String, Object>> result = Optional.ofNullable(someMap.get("id"))
.filter(obj -> obj instanceof List)
.map(obj -> (List<Map<String, Object>>)obj)
.orElse(Collections.emptyList());
在这种情况下,您将有空List
(如果元素未命中或类型不是List
)或预期List
值。