I have a map that is updated from Firebase Realtime Database, so I don't know the map size in advance.
In the map I have a String as key, and a Joda DateTime
as value.
I don't know how to iterate through the map to return the most recent Datetime.
I'll try to explain better:
//on returning results from Realtime Database
Map<String, DateTime> myMap = new HashMap<>();
if(dataSnapshot.exists){
for(DataSnapshot data:dataSnapshot.getChildren()){
String key = data.getKey();
DateTime dateTime = // I get the data and convert it to Datetime; no problem here; I can do it.
myMap.put(key, dateTime);
}
//outside the Loop
//HERE IS WHAT I NEED HELP WITH
for(DateTime date:myMap.values()){
// 1 - check if date is after the next date in map
// 2 - if it is, then keep it
// 3 - if it is not, then remove
// 4 - in the end, only one pair of key/value with the most recent date is left
}
}
Can you guys please, help me? Thank you so much
EDIT: Sorry, one more thing. I'm using a minimum sdk in Android that doesn't ler me use Java 8. I have to use Java 7 features.
how to iterate through the map to return the most recent Datetime
Java 8+ using Streams:
// To get latest key (or entry)
String latestKey = myMap.entrySet().stream()
.max(Entry::comparingByValue)
.map(Entry::getKey) // skip this to get latest entry
.orElse(null);
// To get latest value
DateTime latestValue = myMap.values().stream()
.max(Comparator.naturalOrder())
.orElse(null);
Any Java version using for
loop:
Entry<String, DateTime> latestEntry = null;
for (Entry<String, DateTime> entry : myMap.entrySet()) {
if (latestEntry == null || entry.getValue().isAfter(latestEntry.getValue()))
latestEntry = entry;
}
String latestKey = (latestEntry != null ? latestEntry.getKey() : null);
In the above, adjust as needed depending on whether you need latest key, value, or entry (key+value).
in the end, only one pair of key/value with the most recent date is left
Best way is to replace the map, or at least replace the content, after finding the latest entry.
Java 8+ using Streams (replacing map):
myMap = myMap.entrySet().stream()
.max(Comparator.comparing(Entry::getValue))
.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue));
Any Java version using for
loop (replacing content):
Entry<String, DateTime> latestEntry = null;
for (Entry<String, DateTime> entry : myMap.entrySet()) {
if (latestEntry == null || entry.getValue().isAfter(latestEntry.getValue()))
latestEntry = entry;
}
myMap.clear();
if (latestEntry != null)
myMap.put(latestEntry.getKey(), latestEntry.getValue());