java集合根据字段排序
时间: 2023-09-10 07:10:57 浏览: 53
java中集合排序
Java中的集合可以使用Comparator接口和Comparable接口来进行排序。下面是根据字段排序的示例代码:
假设我们有一个Person类,其中包含两个字段name和age:
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter and setter methods
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
现在我们想按照年龄对Person对象进行排序,可以使用Comparator接口来实现:
```java
List<Person> persons = new ArrayList<>();
persons.add(new Person("Alice", 25));
persons.add(new Person("Bob", 30));
persons.add(new Person("Charlie", 20));
// sort by age in ascending order
Collections.sort(persons, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
});
System.out.println(persons);
```
输出结果:
```
[Person{name='Charlie', age=20}, Person{name='Alice', age=25}, Person{name='Bob', age=30}]
```
如果我们想按照姓名的字母顺序对Person对象进行排序,可以使用Comparable接口来实现:
```java
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter and setter methods
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Person o) {
return this.getName().compareTo(o.getName());
}
}
List<Person> persons = new ArrayList<>();
persons.add(new Person("Alice", 25));
persons.add(new Person("Bob", 30));
persons.add(new Person("Charlie", 20));
// sort by name in ascending order
Collections.sort(persons);
System.out.println(persons);
```
输出结果:
```
[Person{name='Alice', age=25}, Person{name='Bob', age=30}, Person{name='Charlie', age=20}]
```
阅读全文