First self-made class
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;
}
}
Put elements in list and sort
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());
}
}
}
The output result is as follows
suzuki : 20 tanaka : 25 yamada : 28
In ascending order, the second argument of Comparator.comparing () can be omitted In descending order, it is necessary to specify Comparator.reverseOrder () as the second argument.
Comparator<Employee> compare = Comparator.comparing(Employee::getAge,Comparator.reverseOrder());
Recommended Posts