[英]Sorting array of objects by field
我有对象
Person{
String name;
int age;
float gradeAverage;
}
有一种简单的排序方式
Person[] ArrayOfPersons
按年龄?
我必须使用Comparable或Comparator吗? 我不完全理解他们。
为了完整Comparator.comparing(Person::getAge)
,在使用Java 8时,您可以使用Comparator.comparing
为某些属性创建一个简单的比较器,例如Comparator.comparing(Person::getAge)
,或者使用lambda,比如Comparator.comparing(p -> p.age)
,如果没有年龄的getter方法。
这使得使用thenComparing
链接比较器变得特别容易,例如主要按年龄排序,然后在关联的情况下按名称排序:
Comparator.comparing(Person::getAge).thenComparing(Person::getName)
将它与Arrays.sort
结合起来,你就完成了。
Arrays.sort(arrayOfPersons, Comparator.comparing(Person::getAge));
您可以实现Comparable接口以使您的类可比。 确保覆盖compareTo方法。
public class Person implements Comparable<Person> {
String name;
int age;
float gradeAverage;
@Override
public int compareTo(Person p) {
if(this.age < p.getAge()) return -1;
if(this.age == p.getAge()) return 0;
//if(this.age > p.getAge()) return 1;
else return 1;
}
//also add a getter here
}
您可以在循环中使用吸气剂检查年龄
for (int i = 0 ; i < persons.length - 1; i++) {
Person p = persons[i];
Person next = persons[i+1];
if(p.getAge() > next.getAge()) {
// Swap
}
}
但是实现Comparable是一种方便的方法
class Person implements Comparable<Person> {
String name;
int age;
float gradeAverage;
public int compareTo(Person other) {
if(this.getAge() > other.getAge())
return 1;
else if (this.getAge() == other.getAge())
return 0 ;
return -1 ;
}
public int getAge() {
return this.age ;
}
}
您也可以查看Comparable
文档
是的,只需实现Comparable
接口。
这是一个例子:
class Person implements Comparable<Person> {
public int age;
public String name;
public int compareTo(Person other){
return this.age == other.age ? 0 : this.age > other.age ? 1 : -1;
}
}
import java.util.Arrays;
public class PersonCompare {
public static void main(String[] args) {
Person p1 = new Person("Test1",10);
Person p2 = new Person("Test2",12);
Person p3 = new Person("Test3",4);
Person p4 = new Person("Test4",7);
Person[] ArrayOfPersons = {p1,p2,p3,p4};
Arrays.sort(ArrayOfPersons);
for(Person p: ArrayOfPersons) {
System.out.println(p.getName()+"--"+p.getAge());
}
}
}
class Person implements Comparable<Person> {
String name;
int age;
Person(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;
}
@Override
public int compareTo(Person other) {
if(this.getAge() > other.getAge())
return 1;
else if (this.getAge() == other.getAge())
return 0 ;
return -1 ;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.