【问题标题】:Implement compare against Map values实现与地图值的比较
【发布时间】:2017-02-14 13:03:28
【问题描述】:

我需要找到一个 Integer week 配对 Date 是最接近当前时间戳的日期。

换句话说,要与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);
      }

下一个 sn-p 找到最接近当前时间戳的日期:

  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));
      }
  );

MAP_VALUE 参数中应该包含什么才能达到目标?

【问题讨论】:

  • matchMap.values()?

标签: java android dictionary


【解决方案1】:

如果我对您的理解正确,您需要与您的比较器确定的最小值相对应的键。如果是这样,您可以在地图中找到最小条目并提取密钥:

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();

【讨论】:

  • 键是整数,不是日期。
  • @saka1029 谢谢,已修复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 2021-07-14
相关资源
最近更新 更多