order by用java怎么实现
时间: 2024-06-13 11:09:17 浏览: 44
以下是使用Java实现order by的示例代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class OrderByDemo {
public static void main(String[] args) {
// 创建一个Person列表
List<Person> personList = new ArrayList<>();
personList.add(new Person("Tom", 20));
personList.add(new Person("Jerry", 18));
personList.add(new Person("Mike", 22));
personList.add(new Person("Lucy", 19));
// 按照年龄升序排序
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
});
// 输出排序结果
for (Person person : personList) {
System.out.println(person.getName() + " " + person.getAge());
}
}
}
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;
}
}
```
阅读全文