【问题标题】:Sort Array of Hashmap by ascending time按时间升序对 Hashmap 数组进行排序
【发布时间】:2012-10-25 13:14:10
【问题描述】:

我有一个 Hashmap 数组,每个 hashmap 都包含 24 小时时间作为键值对

我想按时间升序对这个数组进行排序。我怎样才能做到这一点?

这是我的代码的 sn-p:

HashMap[] arr = new HashMap[100];

for(int i=0;i<100;i++) {
  HashMap<String,String> child=new HashMap<String,String>();
  child.put("some_time","21:09");  //time changes per iteration(time is in 24-hour format)
  arr[i]=child;
}

【问题讨论】:

  • 有什么理由不简单地使用包含 100 个条目的 HashMap 而不是数组?
  • 我认为 hashmap 不是正确的排序数据结构
  • @assylias, BhavikShah 我怀疑每个有问题的哈希图都包含多个条目;其中一项是排序时间 - 他想按它排序。
  • @assylias:我在 hashmap 中有多个条目;其中一个条目是排序时间 - 我想按它排序。

标签: java arrays time hashmap sorting


【解决方案1】:

以下是按时间对数组进行排序的完整代码,格式为hh:mm

HashMap<String,String>[] harr = new HashMap[10];
final DateFormat df = new SimpleDateFormat("kk:mm");
// prepare your data
for(int i=0;i<harr.length;i++) {
   HashMap<String,String> child=new HashMap<String,String>();
   int ss = (int)(Math.random() * (59 + 1));
   //time changes per iteration(time is in 24-hour format)
   child.put("some_time", String.format("21:%02d", ss));
   harr[i]=child;
}
System.out.printf("map array is: %s%n", Arrays.deepToString(harr));

// now apply sort using a custom method
Arrays.sort(harr, new Comparator<HashMap<String,String>>() {
    public int compare(HashMap<String,String> o1, HashMap<String,String> o2) {
       String t1 = o1.get("some_time");
       String t2 = o2.get("some_time");
       try {
           Date dt1 = df.parse(t1);
           Date dt2 = df.parse(t2);
           return dt1.compareTo(dt2);
       } catch (ParseException e) {
           e.printStackTrace();
       }
       return 0;
    }
});
System.out.printf("sorted map array is: %s%n", Arrays.deepToString(harr));

【讨论】:

  • 感谢您的回答,到目前为止它工作正常,但时间小时包含 12 的条目(例如 12:01,12:34,12:55 等)没有排序并出现在开头数组。
  • @dd619:请尝试使用final DateFormat df = new SimpleDateFormat("kk:mm"); 而不是"hh:mm"
【解决方案2】:

您可以使用Arrays.sort(T[], Comparator&lt;T&gt;)。这允许您传递任何类型的数组并编写自己的自定义比较器方法,如下所示:

Arrays.sort(arr, new Comparator<HashMap>() {
    public int compare(HashMap o1, HashMap o2) {
        // Compare values you're interested in and return int as specified by Comparator API
    }
});

请参阅the API 了解退货详情。

【讨论】:

    【解决方案3】:

    在继续使用这种方法之前,请考虑一下 cmets 并确定 hashmap 数组是否是正确的方法。如果,正如我所指出的,您有一堆地图,每个地图都包含大量信息,其中一个条目是您的日期,那么这可能是正确的做法,在这种情况下,对数组进行排序的最简单方法是使用Arrays.sort 方法:

    HashMap[] arr=new Hashmap[100];
    
    for(int i=0;i<100;i++){
        HashMap<String,String> child=new HashMap<String,String>();
        ... // put all the info into the HashMap
        child.put("some_time","21:09");  //time changes per iteration(time is in 24-hour format)
        arr[i]=child;
    }
    
    Arrays.sort(arr, new Comparator<HashMap>() {
        public int compare(HashMap o1, HashMap o2) {
            String d1 = o1.get("some_time");
            String d2 = o2.get("some_time");
    
            //compare the two dates.  If you're always in the same format, e.g. HH:MM (24 hours, two-digit hour, two-digit year), you might even be able to simply compare strings:
            return d1.compareTo(d2);
        }
    });
    

    【讨论】:

      【解决方案4】:

      一般的方法是编写一个Comparator 来根据键对一对HashMap 对象进行排序,然后将其作为参数传递给Arrays.sort(T[], Comparator&lt;T&gt;) 方法。

      比较器看起来像这样:

          Comparator<HashMap> DATE_ORDER = new Comparator<HashMap>() {
              public int compare(Comparator<HashMap>h1, Comparator<HashMap>h2) {
                  String time1 = h1.get("some_time");
                  String time2 = h2.get("some_time");
                  return time1.compareTo(time2);  // assuming that the time strings
                                                  // can be ordered that way
              }
          };
      

      话虽如此,您的问题是在真正应该编写自定义类时尝试使用 Maps。

      【讨论】:

        【解决方案5】:

        正如 Bhavik 指出的那样,您可能没有充分发挥 JDK 的潜力 - 请查看 SortedMap,这可能正是您正在寻找的;可能使用您自己的Comparator 实现。

        SortedMap arr = new TreeMap<String,HashMap<String,String>>();
        for ( int i=0 ; i<100 ; i++ )
        {
            Map<String,String> child = HashMap<String,String>();
            child.put( "some_time" , "21:09" );
            arr.put( "21:09" , child );
        }
        

        然后你可以使用arr.values().iterator() 来得到你的排序children。

        干杯,

        【讨论】:

        • SortedMap 如何解决这个问题?他想对数组进行排序(SortedMap 是按键排序的,而不是值)。
        猜你喜欢
        • 1970-01-01
        • 2015-02-13
        • 1970-01-01
        • 1970-01-01
        • 2016-02-01
        • 2012-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多