sort string date and sort it

时间:2019-05-31 11:53:23

标签: java sorting compare

I would like to use sort my list of article by date (dd/mm/yyyy). Dates are String.

public class ArticleComparator implements Comparator<Article> {

    @Override
    public int compare(Article a1, Article a2) {
        // TODO Auto-generated method stub
        int result = a1.getDate().compareTo(a2.getDate());
        if(result == 0) 
            result = a1.getAuteur().getPseudo().compareTo(a2.getAuteur().getPseudo());
    return result;
}
public class ReseauSocial {

    private HashMap<String, CompteUtilisateur> utilisateurs; 
    private List <Article> article; 

    public ReseauSocial() {
    }

    public void tirerArticles() {
        Collections.sort(article, new ArticleComparator());
    }

    public void connecter(String pseudo, String mdp) {
    }
}

But can you help me to sort dates from newest to oldest


Thank you for your answer but it does not works.. That is I obtain after modifying my code

public class MainClass {

    static List<Article> articles = new ArrayList<>();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Article a1 = new Article ("article1", "TP1", true, "01/02/2018");
        Article a2 = new Article ("article2", "TP2", true, "01/02/2019");
        articles.add(a1);
        articles.add(a2);

        ReseauSocial rsc = new ReseauSocial(articles);
        rsc.tirerArticles();

        for(int i = 0; i<articles.size(); i++) {
            System.out.print("Articles : "+ articles.get(i).getDate().toString()+"\n");

        }

    }

}
Article 1 : Fri Feb 01 00:00:00 CET 2019
Articles 2 : Thu Feb 01 00:00:00 CET 2018
Articles : 01/02/2018
Articles : 01/02/2019

2 个答案:

答案 0 :(得分:0)

您需要先解析日期

public int compare(Article a1, Article a2) {
   SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
   Date date1 = sdf.parse(a1.getDate());
   Date date2 = sdf.parse(a2.getDate());

   int result = date1.compareTo(date2);
   if(result == 0) { 
      result = a1.getAuteur().getPseudo().compareTo(a2.getAuteur().getPseudo());
   }

   return result;
}

答案 1 :(得分:0)

如果您使用已经相当的数据类型(class的{​​{1}}),
那么您只需返回自己的implements Comparable方法的结果即可:

compareTo
  

请注意,使用public int compare(Article a1, Article a2) { // define a suitable formatter DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy"); // parse both dates LocalDate ldOne = LocalDate.parse(a1.getDate(), dtf); LocalDate ldTwo = LocalDate.parse(a2.getDate(), dtf); // compare the dates and return the result return ldOne.compareTo(ldTwo); } 作为日期通常不是一个好习惯。考虑将代表日期的类属性重构为合适的数据类型。