LoginSignup
4
2

More than 3 years have passed since last update.

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

Posted at

まず自作クラス

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());
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2