输入若干个字符串由小到大排序
时间: 2023-07-26 21:43:46 浏览: 79
可以使用Java中的Arrays.sort()方法来对字符串数组进行排序,示例代码如下:
```java
import java.util.Arrays;
public class SortStrings {
public static void main(String[] args) {
String[] strings = {"apple", "banana", "orange", "pear"};
Arrays.sort(strings);
for (String s : strings) {
System.out.println(s);
}
}
}
```
输出结果为:
```
apple
banana
orange
pear
```
若想按照字符串长度进行排序,可以自定义一个Comparator,示例代码如下:
```java
import java.util.Arrays;
import java.util.Comparator;
public class SortStringsByLength {
public static void main(String[] args) {
String[] strings = {"apple", "banana", "orange", "pear"};
Arrays.sort(strings, Comparator.comparingInt(String::length));
for (String s : strings) {
System.out.println(s);
}
}
}
```
输出结果为:
```
pear
apple
banana
orange
```
阅读全文