java如何list按大小排序
时间: 2024-05-09 13:15:33 浏览: 8
可以使用Java中的Collections.sort()方法来对List进行排序。下面是一个示例代码,演示如何对List中的整数按从小到大的顺序进行排序:
```java
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class SortList {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(5);
numbers.add(20);
numbers.add(15);
System.out.println("Before sorting: " + numbers);
Collections.sort(numbers);
System.out.println("After sorting: " + numbers);
}
}
```
输出结果为:
```
Before sorting: [10, 5, 20, 15]
After sorting: [5, 10, 15, 20]
```
如果想要对List中的对象按照某个属性进行排序,则需要实现Comparator接口,并在sort()方法中传入自定义的Comparator对象。例如,对List中的Person对象按照年龄从小到大进行排序:
```java
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
public class SortList {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("John", 25));
people.add(new Person("Lisa", 30));
people.add(new Person("David", 20));
System.out.println("Before sorting: " + people);
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
});
System.out.println("After sorting: " + people);
}
}
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 name + " (" + age + ")";
}
}
```
输出结果为:
```
Before sorting: [John (25), Lisa (30), David (20)]
After sorting: [David (20), John (25), Lisa (30)]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)