String[]数组排序

xiaoxiao2026-08-14  23

1. String[] 字典顺序排序:

String[] strs = {"a", "d", "c", "f", "e", "g", "h", "b"}; Arrays.sort(strs); /* // 根据需要重写 Comparator Arrays.sort(strs, new Comparator<String>(){ public int compare(String a, String b) { return a.compareTo(b); } }); */ for(String s : strs) { System.out.print(s+" "); } // 输出 // a b c d e f g h  

 

2. String[] 存放数字排序:

String[] strs = {"3", "2", "5", "10", "1", "6", "32", "85"}; // 根据需要重写 Comparator Arrays.sort(strs, new Comparator<String>(){ public int compare(String a, String b) { return (Integer.parseInt(a) > Integer.parseInt(b) ? 1 : -1); } }); for(String s : strs) { System.out.print(s+" "); } // 输出 // 1 2 3 5 6 10 32 85
转载请注明原文地址: https://www.6miu.com/read-5051188.html

最新回复(0)