简体   繁体   中英

Sort Array of Hashmap by ascending time

I have an Array of Hashmap and each hashmap contain 24 hour time as key-value pair .

I want to sort this array in ascending order of time. how can i achieve this?

here is snippet of my code:

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

You can use Arrays.sort(T[], Comparator<T>) . This allows you to pass an array of any type and write your own custom comparator method like this:

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

See the API for details on what to return.

Before proceeding with this approach, do think about the comments and decide whether the array of hashmaps is the right way to go. If, as I pointed out, you have a bunch of maps, each containing large amounts of information, with one entry being your dates, then this may be the right thing to do, in which case the easiest way to sort the array would be to use Arrays.sort method:

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

Here is the full code that will sort the array on time which is in hh:mm format:

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

As Bhavik points out, you may not be using the JDK to it's full potential - have a look at SortedMap which may be just what you're looking for; possibly with your own implementation of a 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 );
}

then you can use arr.values().iterator() to get your sorted child ren.

Cheers,

The general approach is to write a Comparator to order a pair of your HashMap objects based on the key, and then pass that as a parameter to the Arrays.sort(T[], Comparator<T>) method.

Th comparator would look something like this:

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

Having said that, your problem has the "smell" of trying to use Maps when they should really be writing custom classes.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM