Java Collections sort with custom Comparator

Description

Java Collections sort with custom Comparator


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

class Language implements Comparable<Language> {
  String langName, id;//from   w  w w.java2  s  .com

  public Language(String f, String l) {
    this.langName = f;
    this.id = l;
  }

  public String getLangName() {
    return langName;
  }

  public String getId() {
    return id;
  }

  public String toString() {
    return "[ firstname=" + langName + ",id=" + id + "]";
  }

  public int compareTo(Language obj) {
    Language emp = obj;
    int deptComp = langName.compareTo(emp.getLangName());

    return ((deptComp == 0) ? id.compareTo(emp.getId()) : deptComp);
  }

  public boolean equals(Object obj) {
    if (!(obj instanceof Language)) {
      return false;
    }
    Language emp = (Language) obj;
    return langName.equals(emp.getLangName()) && id.equals(emp.getId());
  }
}

class MyComparator implements Comparator<Language> {
  public int compare(Language emp1, Language emp2) {
    int nameComp = emp1.getId().compareTo(emp2.getId());
    return ((nameComp == 0) ? emp1.getLangName().compareTo(emp2.getLangName()) : nameComp);
  }
}

public class Main {
  public static void main(String args[]) {
    ArrayList<Language> names = new ArrayList<Language>();
    names.add(new Language("CSS", "4"));
    names.add(new Language("HTML", "5"));
    names.add(new Language("Java", "1"));
    names.add(new Language("Javascript", "0"));

    for (Language p : names)
      System.out.printf("%-14s ID: %s\n", p.getLangName(), p.getId());
    
    
    System.out.println();
    Collections.sort(names, new MyComparator());
    for (Language p : names)
      System.out.printf("%-14s ID: %s\n", p.getLangName(), p.getId());
  }
}



PreviousNext

Related