• 0

[JAVA] Sorting a set of dates


Question

Hi,

I have a hashmap with filenames as the keys and the related text as its values.

For example:-

Key - mar_2007

Value - March 2007

Key - jun_2008

Value - June 2008

And more like this including variations like may_apr_2008...

How can I sort this data in reverse chronological order i.e latest first...

Please help me with your suggestions.

Link to comment
https://www.neowin.net/forum/topic/681522-java-sorting-a-set-of-dates/
Share on other sites

14 answers to this question

Recommended Posts

  • 0

I think you're gonna have to convert the texts into proper Date vales in order to sort chronologically.

Things like "June 2008" are easy (use SimpleDateFormat), but you will need to code something yourself to cope with "may_apr_2008" (whatever that means!).

  • 0

I'd create a date structure, out it in an ArrayList and then create a comparator and the do Collection.sort();

do a google search on java comparator and collection.sort

public class MyDate implements Comparator{

private int year;

private int month;

... getters and setters, constructor, eqauls()

}

MyDate myDate= new MyDate(1,2006);

myArray.add(myDate);

... etc

myArray.sort(myArray);

  • 0
  _kane81 said:
I'd create a date structure, out it in an ArrayList and then create a comparator and the do Collection.sort();

Date implements Comparable, so you can sort them without having to create a Comparator (unless you want something other than a strictly chronological sort)

  • 0
  _kane81 said:
true, but he isnt specifying a day, guess you could set it to 1... he wants it reversed ... so maybe extend date and override compare and reverse the compare value?

Yes. SimpleDateFormat allows you to parse dates that have things (eg day) missing, so that's OK.

As for the reversed sort... I like your idea - it's almost a one-liner

public int compareTo(Date d) { return - super.compareTo(Date d)}

Its the parsing of the "more like this including variations like may_apr_2008..." that worries me!

  • 0

changed mind :)

my above suggestion is not really good design at all :( - poor seperation of behaviour. You should take a mix of my advice and James.

so here is some example code - seperate out sort behaviour from the object

public class ReverseDateComparator implements Comparator {

	public int compareTo(Date a, Date b) { 
		return - a.compareTo(b)
	}
}

your main
{
   ArrayList<Date> dateList = new ArrayList()

  .. add dates to the list
   dateList.add(new Date());
   .....

  Collection.sort(dateList, new ReverseDateComparator());
}

  • 0

Thanks JamesCherrill and _kane81 :)

I used your ideas and found another solution(may sound wierd)...

My requirement was to get a map with actual filenames as the key and the clean formatted text as the value which is sorted in the chronological order.

for example:-

key = may_2008

value = May 2008

key = mar_16_23_2008

value = May 16-23 2008

key = aug_sep_2007

value = August-September 2007

This must be sorted so that latest docs will be on top. The factor that worried me is the different combinations that can come in the filename part.

Using your suggestions, I extracted a string out of the filename. If the day was specified,I'll use it. Or else I'll put 1 as the day. For month, I took the first month appearing in the name.

Then I parsed it to create a Date object from this string.

I used a TreeMap to store the dates so that it'll be sorted

TreeMap dateList = new TreeMap(Collections.reverseOrder());

The keys were the Date objects and values were the filenames.

I used a LinkedHashMap to retrieve the filenames from the TreeMap.Using a function I formatted the filenames as text to be displayed.

Now the LinkedHashMap contains keys as the filenames and values as the text to be displayed.

Is this a good solution? Or any other optimized solutions are available?

Please put your suggestions.

  • 0

^

hadnt seen "TreeMap(Collections.reverseOrder());" before...

not sure what you are doing there....

I think your solutions sounds fine... however why do you keep using a map? maps are good/quick for lookups on a key. if you just want an ordered list, an arraylist (vector if thread safety is req) would be a better choice as it is more efficent in sorting/ordered stuff.

edit: ok so your keeping a file name link as key... guess thats ok... either that or create a class that encapsulates a date and file name or maybe an actual link to the file....

ie

public class MyFile implements comparable{

File file;

Date date;

public MyFile(File file) {

setFile(file);

}

public void setFile(File file) {

this.file = file;

do some code to parse file name to date

this.date = .....

}

public int compareTo(MyFile file) {

return this.file.getDate().compareTo(file.getDate());

}

}

Edited by _kane81
  • 0

Thanks _kane81 for the valuable inputs.

The existing scenario resembles something like this - in a jsp page, function call is made to get the filenames and the display text. The function is written in a java file and it will return the data in a map.

Now this sorting problem came up and I had to find a solution that will not disrupt the existing system very much.

I used hashMap because I thought it was the best solution. Anyways I need the filenames and the display text built from this filename. By using a Map I can get both with just a single function call.

TreeMap(Collections.reverseOrder()); --> This is a quick solution to reverse the order in Tree Map. As you know, TreeMap sorts in the natural ordering of keys or ascending order. Collections.reverseOrder() will reverse it easily...so I get reverse sorted filename list. Ofcourse it can be done using Comparable interface but this is a very easy and handy solution :) and its working fine...

And I used LinkedHashMap so that the order is preserved as in TreeMap. Thus I can use filenames as keys and display text as values and can be sure that the order is same as the sorted order in TreeMap...

  • 0

Sorry to ressurect this thread but i have a similar problem and wonder if anyone can give me some advices or suggestions.

I am using this method to create a date.

  Quote
public String getDate() {

Calendar cal = Calendar.getInstance();

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

return sdf.format(cal.getTime());

}

Then i store the DATE as the key and a USER object as the value in a Hashmap. Now i will like to sort the KEY (which is the date) with the latest date at the top.

How can i do this? please advice..

Thanks~

  • 0

Oh no! I just realised that i can't do that. Because the date MAY NOT be unique hence cannot be used as a key!

Anyone can give me some suggestions please? Actually the USER object does contain the date. So is there a way i can sort the USER OBJECT according to the dates but calling user.getDate() from the USER OBJECT and maybe store in an arraylist of USER object?

  • 0

i want to sort set of csv files named with dates

like my filename is

beno_hawai_enc_01-Aug-2009.csv

beno_hawai_enc_03-Aug-2009.csv

beno_hawai_enc_02-Aug-2009.csv

how to read these files in sorted order based on filename please give me some ide its very urgent my email id is deepu.bhanu@gmail.com

thank you

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • This sooooo good! 🤣🤣🤣
    • How can all of these Neowin deals be "an all time low price". I find that pretty hard to believe.
    • Oh wow, a patch for an Unreal game to improve performance? We'll see...
    • Get this massive 4TB WD_BLACK SN7100 SSD at a new all-time low price by Taras Buria Xbox owners recently received a new storage upgrade option, which allows them to equip the Xbox Series X|S with 4TB of extra space. That card, however, has an eye-watering price tag—nearly as much as the 1TB Xbox Series S. On the PC side, though, things are much better. Right now, if you need a 4TB SSD without selling a kidney, you can get the WD_BLACK SN7100 PCIe Gen4 SSD. It is now available on Amazon at a new all-time low price after a 16% discount (nearly half the cost of the new 4TB Xbox Storage Expansion Card). The SN7100 is a fast, reliable, and, more importantly, affordable Gen4 solid-state drive. Its speeds are rated up to 7,000MB/s sequential read and 6,700MB/s sequential write, while random input-output speeds are rated at 900K IOPS read and 1,350K IOPS write. These specs are not record-breaking, but they are fast enough for modern gaming (DirectStorage is supported), fast loading times in games and apps, and quick file transfer. The WD_BLACK SN7100 has a limited five-year warranty and endurance rating up to 2,400 TBW. You can monitor the health of your drive in the WD_Black Dashboard app on Windows. As for compatibility, you can use the SN7100 in any PC that accommodates M.2 2280 PCIe Gen4 drives, including PlayStation 5. It is compatible with PCIe Gen3 systems, but the maximum speeds will be limited. 4TB WD_BLACK SN7100 PCIe Gen4 Solid-State Drive - $249.99 | 16% off on Amazon US This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
  • Recent Achievements

    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
    • Week One Done
      CHUNWEI earned a badge
      Week One Done
    • One Year In
      survivor303 earned a badge
      One Year In
    • Week One Done
      jbatch earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      420
    2. 2
      +FloatingFatMan
      186
    3. 3
      snowy owl
      183
    4. 4
      ATLien_0
      179
    5. 5
      Xenon
      140
  • Tell a friend

    Love Neowin? Tell a friend!