JavaでArrays.sortとComparatorを使って配列を並び替える方法

1.Employee.java
public class Employee {
private int age;
private int height;
private String name;
private char sex;

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public char getSex() {
return sex;
}

public void setSex(char sex) {
this.sex = sex;
}

}

2.BinaarrayDemo.java
import java.util.Arrays;
import java.util.Comparator;
public class BinaarrayDemo {

public static void main(String[] args) {

Employee[] emparr = new Employee[5];
emparr[0] = new Employee(“山田", 24, 'f’, 162);
emparr[1] = new Employee(“大崎", 26, 'f’, 160);
emparr[2] = new Employee(“福馬", 27, 'f’, 171);
emparr[3] = new Employee(“麻生", 28, 'm’, 182);
emparr[4] = new Employee(“佐藤", 20, 'm’, 165);

System.out.println(“*****before sort:*****");
for (Employee ep : emparr) {
System.out.println(ep.getName() + “," + ep.getAge() + “,"
+ ep.getSex() + “," + ep.getHeight());
}
/*Arrays.sort(emparr, new Comparator<Employee>() {
public int compare(Employee emp1, Employee emp2) {
return emp1.getAge() – emp2.getAge();
}

});*/
Arrays.sort(emparr, new Comparator<Employee>(){
public int compare(Employee ep1,Employee ep2){
return ep1.getHeight() -ep2.getHeight();
}

});

System.out.println(“—–after sort:—–“);
for (Employee ep : emparr) {
System.out.println(ep.getName() + “," + ep.getAge() + “,"
+ ep.getSex() + “," + ep.getHeight());
}

}

}

3.実行結果
*****before sort:*****
山田,24,f,162
大崎,26,f,160
福馬,27,f,171
麻生,28,m,182
佐藤,20,m,165
—–after sort:—–
大崎,26,f,160
山田,24,f,162
佐藤,20,m,165
福馬,27,f,171
麻生,28,m,182

Java

Posted by arkgame