Posted at

【Java】自作クラスの要素を持つArrayListをソートする

まず自作クラス

public class Employee {

private String name;
private int age;

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

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

listに要素を入れソートしてみる

public class Array {

public static void main(String[] args) {

List<Employee> list = new ArrayList<Employee>();
list.add(new Employee("tanaka", 25));
list.add(new Employee("yamada", 28));
list.add(new Employee("suzuki", 20));

Comparator<Employee> compare = Comparator.comparing(Employee::getAge);
list.sort(compare);

for (Employee e : list) {
System.out.println(e.getName() + " : " + e.getAge());
}
}
}

出力結果は下記のようになる

suzuki : 20

tanaka : 25

yamada : 28

昇順の場合、Comparator.comparing()の第二引数は省略可能

降順の場合は第二引数にComparator.reverseOrder()を指定する必要がある

Comparator<Employee> compare = Comparator.comparing(Employee::getAge,Comparator.reverseOrder());