Sorting Month in Java with Set

(Last Updated On: August 11, 2016)

Program:

package agn;

import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class Sorting {

	public static void main(String[] args) throws ParseException {
		Set<Date> myset = new TreeSet<Date>();
		DateFormat dateFormat = new SimpleDateFormat("MMM");
		myset.add(new java.sql.Date(dateFormat.parse("Apr").getTime()));
		myset.add(new java.sql.Date(dateFormat.parse("jan").getTime()));
		myset.add(new java.sql.Date(dateFormat.parse("dec").getTime()));
		myset.add(new java.sql.Date(dateFormat.parse("feb").getTime()));
		myset.add(new java.sql.Date(dateFormat.parse("jul").getTime()));
		myset.add(new java.sql.Date(dateFormat.parse("sep").getTime()));
		Iterator iter = myset.iterator();
		 DateFormat df = new SimpleDateFormat("MMM");
		while(iter.hasNext()){
			System.out.println(df.format(iter.next()));
		}

	}
}

 

Output:

Jan
Feb
Apr
Jul
Sep
Dec

Thanks for reading this post……!!!

240 total views, 0 views today

Leave a Reply

Your email address will not be published. Required fields are marked *