要按照对象中的不同参数对ArrayList进行排序,可以使用Comparator接口来定义排序规则,并使用Collections.sort()方法对ArrayList进行排序。下面是一个示例代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
class PersonNameComparator implements Comparator {
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
class PersonAgeComparator implements Comparator {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
}
public class Main {
public static void main(String[] args) {
ArrayList persons = new ArrayList<>();
persons.add(new Person("John", 25));
persons.add(new Person("Alice", 18));
persons.add(new Person("Bob", 30));
// 按照姓名排序
Collections.sort(persons, new PersonNameComparator());
System.out.println("按照姓名排序:");
for (Person person : persons) {
System.out.println(person);
}
// 按照年龄排序
Collections.sort(persons, new PersonAgeComparator());
System.out.println("按照年龄排序:");
for (Person person : persons) {
System.out.println(person);
}
}
}
输出结果:
按照姓名排序:
Person{name='Alice', age=18}
Person{name='Bob', age=30}
Person{name='John', age=25}
按照年龄排序:
Person{name='Alice', age=18}
Person{name='John', age=25}
Person{name='Bob', age=30}
上一篇:按照对象值过滤对象数组
下一篇:按照对象中数组的和进行排序