Ivan Fazaniuk Ivan Fazaniuk - 1 month ago 8
Android Question

Implement compare against Map values

I need to find an

Integer
week
which paired
Date
is the closest date to the current timestamp.

In other words to perform a Date compare against values in
matchMap
:

Map<Integer, Date> matchMap = null;
for (MatchSummary match : matchList) {
String str_date = match.getDate();
Date matchDate = null;
try {
matchDate = new SimpleDateFormat("yyyy-MMM-dd'T'HH:mm:ss.SSS'Z'" , Locale.getDefault()).parse(str_date);
} catch (java.text.ParseException e) { e.printStackTrace(); }
matchMap.put(match.getWeek(),matchDate);
}


Next snippet finds the closest date to the current timestamp:

final long now = System.currentTimeMillis();
Date closest = Collections.min(MAP_VALUE, new Comparator<Date>() {
public int compare(Date d1, Date d2) {
long diff1 = Math.abs(d1.getTime() - now);
long diff2 = Math.abs(d2.getTime() - now);
return Long.valueOf(diff1).compareTo(Long.valueOf(diff2));
}
);


What should be in
MAP_VALUE
param to be able then to reach the goal?

Answer

If I understand you correctly, you want the key corresponding to the lowest value, as determined by your comparator. If so, you can find the minimum entry in the map and extract the key:

final long now = System.currentTimeMillis();
Integer closest = Collections.min(matchMap.entrySet(), new Comparator<Map.Entry<Integer, Date>>() {
    @Override
    public int compare(Map.Entry<Integer, Date> e1, Map.Entry<Integer, Date> e2) {
        long diff1 = Math.abs(e1.getValue().getTime() - now);
        long diff2 = Math.abs(e2.getValue().getTime() - now);
        return Long.compare(diff1, diff2);
    }
}).getKey();
Comments