java 字符串list 排序
时间: 2023-09-08 07:12:26 浏览: 95
你可以使用 `Collections.sort()` 方法对字符串列表进行排序,示例如下:
```java
import java.util.Collections;
import java.util.List;
public class SortListExample {
public static void main(String[] args) {
List<String> stringList = List.of("apple", "banana", "pear", "orange");
System.out.println("Before sorting: " + stringList);
Collections.sort(stringList);
System.out.println("After sorting: " + stringList);
}
}
```
输出结果为:
```
Before sorting: [apple, banana, pear, orange]
After sorting: [apple, banana, orange, pear]
```
如果你需要按照自定义的顺序进行排序,可以实现 `Comparator` 接口并传递给 `Collections.sort()` 方法,示例如下:
```java
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortListExample {
public static void main(String[] args) {
List<String> stringList = List.of("apple", "banana", "pear", "orange");
System.out.println("Before sorting: " + stringList);
Collections.sort(stringList, new LengthComparator());
System.out.println("After sorting: " + stringList);
}
static class LengthComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
}
}
```
输出结果为:
```
Before sorting: [apple, banana, pear, orange]
After sorting: [pear, apple, banana, orange]
```
阅读全文