I have map in this format,
HashMap<String, Object> map = {"RequestsServed":{"2019-06-28T00:00:00Z":0.0},"PullRequests":{"2019-06-28T00:00:00Z":0.0}}
My intension is to do map.get("RequestsServed")
and get a map of {"2019-06-28T00:00:00Z":0.0}
irrespective of number of key, value pair in it.
I tried using,
HashMap<DateTime, Object> result = new ObjectMapper().readValue(SerializationUtils.toJson(map.get("RequestsServed").toString()), HashMap.class);
and failed. please help. Thanks
I was so dumb asking this question...
map.get("RequestsServed") is gonna give me a LinkedTreeMap. I just have to parse it into a HashMap of my choice.
serialising map.get("RequestsServed") to a json and parse the resultant value to HashMap will give me the required result easily.
Thank you all for your time.
I have written a dummy class for testing purpose:
public class TempObject {
private String date;
private Double value;
public TempObject(String date, Double value) {
this.date = date;
this.value = value;
}
public String getDate() {
return date;
}
public Double getValue() {
return value;
}
}
And here is your solution:
// Initializing the Map (I'm using LinkedHashMap here for a reason)
Map<String, Object> map = new LinkedHashMap<>();
map.put("RequestsServed", new TempObject("2019-06-28T00:00:00Z", 0.0));
map.put("PullRequests", new TempObject("2019-06-28T00:00:00Z", 0.1));
// Using Collectors.toMap() with mergeFunction (to handle duplicate keys)
Map<String, Object> result = map.values().stream().map(object -> (TempObject) object).collect(Collectors.toMap(TempObject::getDate, TempObject::getValue, (existingValue, newValue) -> newValue));
System.out.println(result); // printing the value of result map: {2019-06-28T00:00:00Z=0.1}
You can also parse this String value to LocalDateTime
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.