Java カスタムソート:Comparatorを使った並び替え
Comparatorインタフェースを使用して、カスタムソーティング規則を実装することができます。Comparatorインタフェースには、カスタムソーティング規則を定義するためのcompareメソッドが含まれています。
例えば、Studentクラスがあるとします。このクラスには名前と年齢の属性が含まれています。年齢の若い順ではなく、年齢の大きい順にStudentオブジェクトを並べ替えたいと思います。
import java.util.Comparator;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class AgeComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
if (s1.getAge() < s2.getAge()) {
return 1;
} else if (s1.getAge() > s2.getAge()) {
return -1;
} else {
return 0;
}
}
}
その後、使用する際に、AgeComparatorをCollections.sortメソッドに渡すことで、Studentオブジェクトをカスタムソートできます。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 22));
students.add(new Student("Charlie", 18));
Collections.sort(students, new AgeComparator());
for (Student student : students) {
System.out.println(student.getName() + " - " + student.getAge());
}
}
}
学生情報は、年齢の降順で出力されます。