Java List sort custom object on enum field

Description

Java List sort custom object on enum field




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

enum Level {
  HIGH, MEDIUM, LOW;//  w ww.  j a va2 s  . co  m
}

class Language {
  private Level severity;
  private String name;

  public Language(Level severity, String name) {
    super();
    this.severity = severity;
    this.name = name;
  }

  public Level getSeverity() {
    return severity;
  }

  public void setSeverity(Level severity) {
    this.severity = severity;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

class MyComparator implements Comparator<Language> {
  @Override
  public int compare(Language person1, Language person2) {
    if (person1.getSeverity() == person2.getSeverity()) {
      return person1.getName().compareTo(person2.getName());
    } else {
      return person1.getSeverity().compareTo(person2.getSeverity());
    }
  }
}
public class Main {
  public static void main(String[] args) {
    Language one = new Language(Level.HIGH, "CSS");
    Language two = new Language(Level.MEDIUM, "HTML");
    Language three = new Language(Level.LOW, "Java");
    Language four = new Language(Level.HIGH, "Javascript");
    Language five = new Language(Level.MEDIUM, "SQL");
    Language six = new Language(Level.LOW, "SQL");
    Language seven = new Language(Level.LOW, "C++");

    List<Language> persons = new ArrayList<Language>();
    persons.add(one);
    persons.add(two);
    persons.add(three);
    persons.add(four);
    persons.add(five);
    persons.add(six);
    persons.add(seven);

    Collections.sort(persons, new MyComparator());
    for (Language person : persons) {
      System.out.println(person.getName() + " " + person.getSeverity());
    }
  }
}



PreviousNext

Related