Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort the hashset based on date

Tags:

java

How can i sort the data inside a hashset based on date

I have a program in which i will get the data from mongodb in this format 2015-01-17 and later i will convert it to MMM dd yyyy format and now how can i sort the data here ??

This is my program

public class MyObject {

    public static void main(String args[]) {
        String sym = "BAC";
        Set<String> set = myDAO.getInstance().getMeAllExpirationDates(sym);
        for (String String : set) {

            System.out.println(String);
        }
    }

    public Set<String> getMeAllExpirationDates(String sym) throws Exception {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd yyyy");
        Set<String> set = new HashSet<String>();

        BasicDBObject query = new BasicDBObject();
        query.put("symbol", sym);
        Security sec = null;
        DBCursor cursor = collection.find(query);
        while (cursor.hasNext()) {
            sec = (Security) cursor.next();
            Date date = sdf1.parse(sec.getTkExpirationDate());
            String result = sdf2.format(date);
            set.add(result);
        }
        return set;
    }
}
like image 355
Pawan Avatar asked Nov 26 '25 06:11

Pawan


1 Answers

HashSet is an unordered collection - its elements are not stored in any particular order. You can regard HashSet as a bag that contains items - the items are all in the bag, but not in any particular order.

If you want a Set that contains elements in a specific order, use an implementation of SortedSet, for example TreeSet, instead of HashSet.

TreeSet by default stores its elements in "natural order", if you want a different order you can use the TreeSet constructor that takes a Comparator; supply your own Comparator that defines the order you want the elements to be sorted in.

like image 125
Jesper Avatar answered Nov 28 '25 19:11

Jesper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!