2

I want to sort month names. I have tried the following:

import java.util.SortedSet;
import java.util.TreeSet;

public class SortingMonth {

    public static void main(String[] args) {
        SortedSet<String> monthSet = new TreeSet<String>();
        monthSet.add("Feb");
        monthSet.add("Jan");
        monthSet.add("Mar");
        monthSet.add("Dec");
        monthSet.add("Aug");

        for(String value:monthSet){
            System.out.println(value);
        }
    }
}

Output:

Aug
Dec
Feb
Jan
Mar

But I want the output in this order:

Jan
Feb
Mar
Aug
Dec
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
Naveen
  • 367
  • 2
  • 4
  • 11

7 Answers7

2

May be you can try different way as following. Best efficient way to sort Months and Year in Java

List<String> abc = new ArrayList<String>();
    List<Date> xyz = new ArrayList<Date>();

    abc.add("JAN-2010");
    abc.add("JAN-2011");
    abc.add("APR-2013");
    abc.add("NOV-2009");

    try {

        for (String abc1 : abc) {

            Date date;

            date = new SimpleDateFormat("MMM-yyyy", Locale.ENGLISH)
                    .parse(abc1);
            xyz.add(date);

        }

        Collections.sort(xyz, new Comparator<Date>() {

            public int compare(Date arg0, Date arg1) {
                // return arg0.getDate().compareTo(o2.getDate());
                return arg0.compareTo(arg1);
            }
        });

        for (Date date1 : xyz) {
            System.out.println("Sorted : " + date1);
        }

    } catch (ParseException e) {

        e.printStackTrace();

    }
}
Community
  • 1
  • 1
Ahmet Karakaya
  • 9,899
  • 23
  • 86
  • 141
2

Use a comparator in your TreeSet like this:

SortedSet<String> monthSet = new TreeSet<String>(new Comparator<String>() {
    public int compare(String o1, String o2) {
        try {
            SimpleDateFormat fmt = new SimpleDateFormat("MMM", Locale.US );
            return fmt.parse(o1).compareTo(fmt.parse(o2));
        } catch (ParseException ex) {
            return o1.compareTo(o2);
        }
    }
});

That is not very efficient but as close to your example code as possible.

halfbit
  • 3,414
  • 1
  • 20
  • 26
0

If you do not tell the TreeSet which ordering you want, it will use standard string ordering (alphabetic).

Use the constructor that takes a Comparator<String> and create an instance that sorts the values as you wish.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
  • Oh, and most of the comments to your question are insightful... my answer is only useful if you stick to use that structure, and because it helps you understand what is happenning. – SJuan76 Nov 15 '13 at 22:13
  • @nikpon it is hard to understand what do you mean. – SJuan76 Nov 15 '13 at 22:29
0

There is no OOTB way to achieve this. You would need to hardcore somewhere (be it in comparator or in some custom utility that might use month to handle this) the order of months

user1339772
  • 783
  • 5
  • 19
0

Depending on what else you'd like to do with the months, perhaps creating an enum type for them would be worthwhile. See here:

http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Dawn
  • 93
  • 7
0

If you make Month into an enum, this is very easy:

import java.util.SortedSet;
import java.util.TreeSet;

class SortingMonth {

  enum Month {
    Jan(1, "January"),
    Feb(2, "February"),
    Mar(3, "March"),
    //..
    Aug(8, "August"),
    //...
    Dec(12, "December");
    int id;
    String text;
    Month(int id, String text) {
      this.id = id;
      this.text = text;
    }
    public String text() {
      return text;
    }
    public int id() {
      return id;
    }
  }


  public static void main(String[] args) {
      SortedSet<Month> monthSet = new TreeSet<Month>();
      monthSet.add(Month.Feb);
      monthSet.add(Month.Jan);
      monthSet.add(Month.Mar);
      monthSet.add(Month.Dec);
      monthSet.add(Month.Aug);

      for(Month value:monthSet){
          System.out.println(value);
      }

  }

}
agbinfo
  • 793
  • 5
  • 17
  • In this case, you don't even need the enum constructors and member functions but if you wanted to print the full month you could do: `println(value.text())` – agbinfo Nov 15 '13 at 22:35
-1

If you need a Set<String> with the names of the months and sorted, you may use a LinkedHashSet<String>. From its javadoc (emphasis mine):

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order).

So, just do this:

Set<String> months = new LinkedHashSet<String>();
months.add("Jan");
months.add("Feb");
months.add("Aug");
months.add("Dec");
System.out.println(months);

Output:

[Jan, Feb, Aug, Dec]
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • LinkedHashSet just gives the order of the same insertion order right ? Here my requirement is what ever the order may be But I want in the month order...... – Naveen Nov 15 '13 at 23:34
  • Set months = new LinkedHashSet(); months.add("Feb"); months.add("Aug"); months.add("Dec"); months.add("Jan"); System.out.println(months); Will Give Wrong results. – Parthasarathy B May 23 '14 at 13:00
  • @ParthasarathyB that's because you're using the `LinkedHashSet` in the wrong way... Did you at least read my proposed example about **how to use it**? – Luiggi Mendoza May 23 '14 at 14:33
  • @Luiggi, your answer for this particular post doesnot solve my problem. – Parthasarathy B Jun 13 '14 at 06:10
  • @ParthasarathyB if you post which specific problem you have, then you would get better help. – Luiggi Mendoza Jun 13 '14 at 06:12