java list string排序
时间: 2023-08-12 22:36:22 浏览: 83
可以使用Collections.sort(List<T>)方法对List<String>进行排序。示例如下:
```java
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = List.of("apple", "banana", "orange", "pear");
Collections.sort(list);
System.out.println(list);
}
}
```
输出结果为:
```
[apple, banana, orange, pear]
```
如果要实现自定义排序,可以使用Comparator接口,示例如下:
```java
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = List.of("apple", "banana", "orange", "pear");
Collections.sort(list, new StringLengthComparator());
System.out.println(list);
}
}
class StringLengthComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
}
```
输出结果为:
```
[pear, apple, banana, orange]
```
阅读全文