解决方法1:使用Arrays.sort()进行排序
import java.util.Arrays;
public class SortArray {
public static void main(String[] args) {
int[] array = {5, 3, 9, 1, 7};
// 使用Arrays.sort()进行排序
Arrays.sort(array);
// 输出排序后的数组
System.out.println(Arrays.toString(array));
}
}
解决方法2:使用map进行排序
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class SortMap {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("John", 5);
map.put("Amy", 3);
map.put("David", 9);
map.put("Bob", 1);
map.put("Cindy", 7);
// 使用TreeMap对map进行排序
Map sortedMap = new TreeMap<>(map);
// 输出排序后的map
for (Map.Entry entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
以上代码示例分别演示了使用Arrays.sort()和使用map进行排序的方法。第一个示例使用Arrays.sort()对一个整数数组进行排序,而第二个示例使用TreeMap对一个键值对的map进行排序。