Search code examples
javasortingcollectionspojo

How to sort collection according particular field value of POJO?


I have one below mentioned class (POJO),

public class DummyPage{

   public DummyPage(int id, String month){
     this.id = id;
     this.month = month;
   }

   public DummyPage(){
   }

   private int id
   private String  month;

   //getter and setters
}

and also piece of code

public static void main(String[] args){

   List<DummyPage> list = new ArrayList<DummyPage>();
   list.add(new DummyPage(1,"March"));
   list.add(new DummyPage(2,"September"));
   list.add(new DummyPage(3,"December"));
   list.add(new DummyPage(4,"May"));
   list.add(new DummyPage(5,"April"));
   list.add(new DummyPage(6,"January"));
   list.add(new DummyPage(7,"August"));
   list.add(new DummyPage(8,"March"));
   list.add(new DummyPage(9,"December"));
   list.add(new DummyPage(10,"October"));
   list.add(new DummyPage(11,"July"));
   list.add(new DummyPage(12,"November"));
   list.add(new DummyPage(13,"February"));
   list.add(new DummyPage(14,"May"));
   list.add(new DummyPage(15,"June"));      

}

My actual POJO have more fields and also actually list have more objects.

Expected Result :
I need to sort declared list according to month name wise.
All objects with January month name must come first in output list.
All objects with February month name must come second in output list.
etc.. for all the months.

Which is the best way to sort these type of objects in given manner? Can I use Comparator? If yes, how can I implement it? Thanks in advance.


Solution

  • You can define a custom comparator and pass it to Collections.sort(), as suggested by @Robby, you can use Month enum like

    public class CustomComparator implements Comparator<DummyPage> {
        @Override
        public int compare(DummyPage o1, DummyPage o2) {
            return Month.valueOf(o1.getMonth().toUpperCase()).compare(Month.valueOf(o2.getMonth().toUpperCase()));
        }
    }
    

    and

    Collections.sort(list , new CustomComparator());
    

    Also looks like you already have month number in DummyPage.id field, it can be used directly in compare method of comparator. Or if you are looking for how to convert month name to number, you can use SimpleDateFormat

    public int convertMonthToNumber(String month){
         Date date = new SimpleDateFormat("MMMM", Locale.ENGLISH).parse(month);
         Calendar cal = Calendar.getInstance();
         cal.setTime(date);
         return cal.get(Calendar.MONTH);
    }