Java Arrays sort custom object via Comparator

Description

Java Arrays sort custom object via Comparator


import java.util.Arrays;
import java.util.Comparator;

public class Main {
  public static void main(String[] args) {
    Language[] myArray = new Language[5];
    myArray[0] = new Language("CSS", 15);
    myArray[1] = new Language("HTML", 12);
    myArray[2] = new Language("Java", 15);
    myArray[3] = new Language("Javascript", 18);
    myArray[4] = new Language("SQL", 37);
    //from w w  w . ja  v  a2s .c o  m
    Arrays.sort(myArray, Language.NAME_COMPARATOR);
    System.out.println(Arrays.toString(myArray));
    Arrays.sort(myArray, Language.AGE_COMPARATOR);
    System.out.println(Arrays.toString(myArray));
  }
}

class Language {
  public static Comparator<Language> AGE_COMPARATOR = new Comparator<Language>() {
    @Override
    public int compare(final Language o1, final Language o2) {
      return Integer.valueOf(o1.age).compareTo(o2.age);
    }
  };
  //Lambda expression
  public static Comparator<Language> NAME_COMPARATOR = (Language o1, Language o2) ->{
    return o1.name.compareTo(o2.name);
  };
  
  String name;
  int age;

  public Language(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String toString() {
    return "[name: " + name + ", age: " + age + "]";
  }
}



PreviousNext

Related