Java sort List by date as String

前端 未结 2 1221
不知归路
不知归路 2021-01-26 05:50

I have a list from the Type and I would like to sort this list by an element of date. I googled and I saw some solutions with comparable, but is there a possibility to do this

相关标签:
2条回答
  • 2021-01-26 06:36

    So if date is stored in varchar2 than firstly Convert them to an actual Date object,

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:m");
    System.out.println(sdf.parse(dateFromDataBase));
    

    and then do the comparing on date Objects

    if(date1.compareTo(date2)>0){
    // Do whatever you want to do 
    }
    

    Now coming to the sorting of List<SqlRow>

    you can use comparator Interface as mentioned by @Srinivasu Talluri but if you are not interested in using these interfaces which literally make you life easy than you can use either bubble sort or Insertion sort and compare on the basis of dates as mentioned above

    0 讨论(0)
  • 2021-01-26 06:54
    Collections.sort(Type, new Comparator<Type>() {
        @Override
        public int compare(Type o1, Type o2) {
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:m");
              Date d1 = sdf.parse(o1.date);
              Date d2 = sdf.parse(o2.date);
              return d1.compareTo(d2);
          }
      });
    
    0 讨论(0)
提交回复
热议问题