您可以使用内置的排序算法(或您自己的)按字母顺序排序,术语是字典顺序的。例如通过使用Collections#sort
(文档)。请注意,String
s 是可比较的,默认情况下使用字典顺序。这就是您不需要显式指定顺序的原因,例如通过使用Comparator
对象。
此代码段对城市进行排序并打印它们:
List<String> cities = Arrays.asList({city1, city2, city3});
Collections.sort(cities);
System.out.println("Cities sorted lexicographical:");
for (String city : cities) {
System.out.println(city);
}
或者,如果您更喜欢使用紧凑的Java 8解决方案Streams
(它基本上回退到相同的方法,尤其是相同的排序方法):
Stream.of(city1, city2, city3).sorted().forEach(System.out::println);
请注意,该String#compareTo
方法还比较字典顺序,如前所述。因此,您也可以直接对比较进行硬编码(就像您已经尝试过的那样),而不是使用排序算法(compareTo
以一种聪明的方式检查结果):
String smallestCity;
if (city1.compareTo(city2) < 0 && city1.compareTo(city3) < 0) {
smallestCity = city1;
} else if (city2.compareTo(city1) < 0 && city2.compareTo(city3) < 0) {
smallestCity = city2;
} else if (city3.compareTo(city1) < 0 && city3.compareTo(city2) < 0) {
smallestCity = city3;
} else {
throw new AssertionError("There is no strict order!");
}
String biggestCity;
if (city1.compareTo(city2) > 0 && city1.compareTo(city3) > 0) {
biggestCity = city1;
} else if (city2.compareTo(city1) > 0 && city2.compareTo(city3) > 0) {
biggestCity = city2;
} else if (city3.compareTo(city1) > 0 && city3.compareTo(city2) > 0) {
biggestCity = city3;
} else {
throw new AssertionError("There is no strict order!");
}
String middleCity;
if (city1.compareTo(smallestCity) > 0 && city1.compareTo(biggestCity) < 0) {
middleCity = city1;
} else if (city2.compareTo(smallestCity) > 0 && city2.compareTo(biggestCity) < 0) {
middleCity = city2;
} else if (city3.compareTo(smallestCity) > 0 && city3.compareTo(biggestCity) < 0) {
middleCity = city3;
} else {
throw new AssertionError("There is no strict order!");
}
如果元素相等、第一个元素小于并且大于第二个元素(文档) ,则该方法String#compareTo
返回。0
< 0
> 0
但如前所述,排序算法以更聪明的方式执行这些检查,比较少。所以你应该使用一个。