Java List sort custom object on various attributes

Description

Java List sort custom object on various attributes


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

class Language {//from w  w  w . j  av  a 2  s .com
  public String name;
  public int id;
  public Date learnDate;

  public Language(String iname, int i, Date d) {
    name = iname;
    id = i;
    learnDate = d;
  }

  public String toString() {
    return name + " " + id + " " + learnDate.toString();
  }

}

// Comparator
class CompId implements Comparator<Language> {
  @Override
  public int compare(Language arg0, Language arg1) {
    return arg0.id - arg1.id;
  }
}

class CompDate implements Comparator<Language> {
  private int mod = 1;

  public CompDate(boolean desc) {
    if (desc)
      mod = -1;
  }

  @Override
  public int compare(Language arg0, Language arg1) {
    return mod * arg0.learnDate.compareTo(arg1.learnDate);
  }
}

public class Main {
  public static void main(String[] args) {
    SimpleDateFormat df = new SimpleDateFormat("mm-dd-yyyy");
    ArrayList<Language> people = new ArrayList<Language>();
    try {
      people.add(new Language("CSS", 9, df.parse("12-12-2014")));
      people.add(new Language("HTML", 2, df.parse("1-12-2013")));
      people.add(new Language("Java", 4, df.parse("12-2-2012")));
    } catch (ParseException e) {
      e.printStackTrace();
    }

    Collections.sort(people, new CompId());
    System.out.println("BY ID");
    for (Language p : people) {
      System.out.println(p.toString());
    }

    Collections.sort(people, new CompDate(false));
    System.out.println("BY Date asc");
    for (Language p : people) {
      System.out.println(p.toString());
    }
    Collections.sort(people, new CompDate(true));
    System.out.println("BY Date desc");
    for (Language p : people) {
      System.out.println(p.toString());
    }

  }

}



PreviousNext

Related