赞
踩
无论是基本类型的数组还是包装类型的数组, 都可以用 Arrays.sort( ) 来排序
int[] arr = {10, 7, 8, 9, 1, 8, 5};
// 升序
Arrays.sort(arr);
//输出:[1, 5, 7, 8, 8, 9, 10]
System.out.println(Arrays.toString(arr));
对于基本类型的数组,可以使用 IntStream 进行装箱然后排序
int[] arr = {10, 7, 8, 9, 1, 8, 5};
// 升序
arr = IntStream.of(arr).boxed().sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
//输出:[10, 9, 8, 8, 7, 5, 1]
System.out.println(Arrays.toString(arr));
对于包装类型的数组,可以先升序然后再翻转
Integer[] arr = {10, 7, 8, 9, 1, 8, 5};
// 升序
Arrays.sort(arr);
Arrays.sort(arr, Collections.reverseOrder());
//输出:[10, 9, 8, 8, 7, 5, 1]
System.out.println(Arrays.toString(arr));
List<Integer> intList = Arrays.asList(10, 7, 8, 9, 1, 8, 5);
Collections.sort(intList); //[1, 5, 7, 8, 8, 9, 10]
List<Integer> intList = Arrays.asList(10, 7, 8, 9, 1, 8, 5);
intList.sort(Collections.reverseOrder()); //[10, 9, 8, 8, 7, 5, 1]
//或者使用 Collections.sort 来降序
//Collections.sort(intList,Collections.reverseOrder());
//或者先升序排序,再翻转
//Collections.sort(intList);
//Collections.reverse(intList);
假设我有如下待排序的字符串:
"salesgroup", "asstacttype", "asstact", "salesman", "currency", "basecurrency", "org", "billtypeid"
期望按照如下的字符串顺序进行排序:
"org", "asstacttype", "asstact", "salesorg", "salesdept", "salesgroup", "salesman", "billtypeid", "currency", "basecurrency"
排序方式:
//待排序的list List<String> inputList = new ArrayList<>(Arrays.asList("salesgroup", "asstacttype", "asstact", "salesman", "currency", "basecurrency", "org", "billtypeid")); // 定义排序顺序 List<String> sortOrder = Arrays.asList("org", "asstacttype", "asstact", "salesorg", "salesdept", "salesgroup", "salesman", "billtypeid", "currency", "basecurrency"); // 创建一个自定义的Comparator,按照 sortOrder 顺序排序 Comparator<String> customComparator = (s1, s2) -> { int s1Index = sortOrder.indexOf(s1); int s2Index = sortOrder.indexOf(s2); if (s1Index == -1 || s2Index == -1) { return s1.compareTo(s2); //如果某个元素不在排序顺序中,就按字典序排序 } return s1Index - s2Index; //按排序顺序排序 }; // 使用自定义的Comparator对inputList进行排序 inputList.sort(customComparator); //输出:[org, asstacttype, asstact, salesgroup, salesman, billtypeid, currency, basecurrency] System.out.println(inputList);
List<String> list = new ArrayList<>();
list.add("F:/山下海棠/第10章 神奇的力量.md");
list.add("F:/山下海棠/第1111章 魔界.md");
list.add("F:/山下海棠/第2章 出发.md");
list.add("F:/山下海棠/第2522章 大结局.md");
list.add("F:/山下海棠/第25章 新伙伴.md");
list.add("F:/其他文件.txt");
list.add("F:/山下海棠/指南.md");
假设上面的 list 存储的是小说章节,需要根据其章节数字进行升序排序,如果字符串中没有 第xx章,就将其放到最后。
排序方式:
import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class MainServer { public static void main(String[] args) throws IOException { List<String> list = new ArrayList<>(); list.add("F:/山下海棠/第10章 神奇的力量.md"); list.add("F:/山下海棠/第1111章 魔界.md"); list.add("F:/山下海棠/第2章 出发.md"); list.add("F:/山下海棠/第2522章 大结局.md"); list.add("F:/山下海棠/第25章 新伙伴.md"); list.add("F:/其他文件.txt"); list.add("F:/山下海棠/指南.md"); list.sort(Comparator.comparingInt(MainServer::extractNumber)); System.out.println(list); } private static int extractNumber(String s) { try { String number = s.split("章")[0].replaceAll("[^0-9]", ""); return Integer.parseInt(number); } catch (Exception e) { return Integer.MAX_VALUE; } } }
输出:
[F:/山下海棠/第2章 出发.md, F:/山下海棠/第10章 神奇的力量.md, F:/山下海棠/第25章 新伙伴.md, F:/山下海棠/第1111章 魔界.md, F:/山下海棠/第2522章 大结局.md, F:/其他文件.txt, F:/时空之戒/指南.md]
在上面的代码中,使用 Comparator.comparingInt 方法创建一个 Comparator,它根据我们定义的 extractNumber 方法对字符串进行排序。extractNumber 方法通过正则表达式将字符串中的数字部分提取出来,并将其转换为整数。
首先,使用 split(“章”) 将字符串在"章"字处分割成两部分。然后,使用 replaceAll(“[^0-9]”, “”) 将第一部分中的非数字字符替换为空字符串,只保留数字部分。最后,将数字部分转换为整数,并返回它作为排序的优先级。
如果在字符串中没有找到 “第” 和 “章”,则 split(“章”) 将返回一个只包含一个空字符串的数组。在这种情况下,我们使用replaceAll(“[^0-9]”, “”) 将数字部分转换为整数,但是由于没有数字存在,它将返回一个无效的整数(例如 Integer.parseInt(“”) 将返回0)。为了让这类字符串排到最后,我们使用 Integer.MAX_VALUE 作为它们的优先级。
通过调用 list.sort 方法对字符串列表进行排序,根据我们定义的 Comparator 进行排序。排序后,输出结果将按照你要求的规则进行排序,包含数字的字符串将按照数字大小排序,没有数字的字符串将排在最后。
使用 TreeMap ,TreeMap 会根据key对put进去的 key 进行升序排序。
Map<Integer,String> treeMap = new TreeMap<>();
treeMap.put(1,"111");
treeMap.put(8,"888");
treeMap.put(4,"444");
treeMap.put(2,"222");
System.out.println(treeMap); //输出{1=111, 2=222, 4=444, 8=888}
Map<Integer,String> treeMap = new TreeMap<>(Comparator.reverseOrder());
treeMap.put(1,"111");
treeMap.put(8,"888");
treeMap.put(4,"444");
treeMap.put(2,"222");
System.out.println(treeMap);//输出{8=888, 4=444, 2=222, 1=111}
(注:不推荐用 Double 作为Map 的 key,由于Map的底层 hashcode 的实现,会导致取出数据时有时有问题。如果可以确定小数点后的位数,比如小数点后只有两位小数,可以乘以100 化为 Integer 作为 key,要取出来时除以 100 再取 )
对value降序:
Map<String, Double> budget = new HashMap<>();
budget.put("普通账户", 1000.00);
budget.put("信用账户", 2000.00);
budget.put("期权账户",500.00);
budget.put("理财账户", 4000.00);
//jdk8通过stream实现对Map降序排序
Map<String, Double> sorted = budget
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
//sorted为{理财账户=4000.0, 信用账户=2000.0, 普通账户=1000.0, 期权账户=500.0}
对 key 降序并只要前2个:
Map<String, Double> budget = new HashMap<>();
budget.put("普通账户", 1000.00);
budget.put("信用账户", 2000.00);
budget.put("期权账户",500.00);
budget.put("理财账户", 4000.00);
//jdk8通过stream实现对Map降序排序
Map<String, Double> sorted = budget
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.limit(2)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
//sorted为{理财账户=4000.0, 信用账户=2000.0}
System.out.println(sorted);
对value升序:
Map<String, Double> budget = new HashMap<>();
budget.put("普通账户", 1000.00);
budget.put("信用账户", 2000.00);
budget.put("期权账户",500.00);
budget.put("理财账户", 4000.00);
//jdk8通过stream实现对Map升序排序
Map<String, Double> sorted = budget
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.naturalOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
//sorted为{期权账户=500.0, 普通账户=1000.0, 信用账户=2000.0, 理财账户=4000.0}
参考网址:Java8中对HashMap的Value值进行排序
List<Map<String, Object>> resultlist = new ArrayList<>(); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("id", "1"); map1.put("name", "张三"); map1.put("Score", 86.5); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("id", "2"); map2.put("name", "李四"); map2.put("Score", 90.0); Map<String, Object> map3 = new HashMap<String, Object>(); map3.put("id", "3"); map3.put("name", "王五"); map3.put("Score", 70.5); resultlist.add(map1); resultlist.add(map2); resultlist.add(map3); resultlist.sort((o1, o2) -> { Double one = Double.valueOf(o1.get("Score").toString()); Double two = Double.valueOf(o2.get("Score").toString()); return one.compareTo(two); //one.compareTo(two)为升序,two.compareTo(one)为降序 }); // 下面注释的代码是老式的写法,有点冗长,已不推荐 // Collections.sort(resultlist, new Comparator<Map<String, Object>>() { // @Override // public int compare(Map<String, Object> o1, Map<String, Object> o2) { // Double one = (Double) o1.get("Score"); // Double two = (Double) o2.get("Score"); // return one.compareTo(two); //one.compareTo(two)为升序,two.compareTo(one)为降序 // } // }); //输出[{Score=70.5, name=王五, id=3}, {Score=86.5, name=张三, id=1}, {Score=90.0, name=李四, id=2}] System.out.println(resultlist);
Student类:
public class Student { private String name; private int score; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } }
对List<Student>排序:
List<Student> list = new ArrayList<>(); Student student1=new Student(); Student student2=new Student(); Student student3=new Student(); student1.setName("张三"); student1.setScore(92); student2.setName("李四"); student2.setScore(86); student3.setName("王五"); student3.setScore(100); list.add(student1); list.add(student2); list.add(student3); System.out.println("排序前:"); for(int i = 0;i < list.size();i++){ System.out.println(list.get(i).getName()+":"+list.get(i).getScore()); } System.out.println("--------"); System.out.println("排序后:"); //升序 list.sort(Comparator.comparingInt(Student::getScore)); //降序 //list.sort((o1, o2) -> o2.getScore() - o1.getScore()); // 下面注释的是老式的升序方式,比较冗长,已不推荐 // Collections.sort(list, new Comparator<Student>() { // @Override // public int compare(Student o1, Student o2) { // int i = o1.getScore() - o2.getScore(); // return i; // } // }); for(int i = 0;i < list.size();i++){ System.out.println(list.get(i).getName()+":"+list.get(i).getScore()); }
结果:
排序前:
张三:92
李四:86
王五:100
--------
排序后:
李四:86
张三:92
王五:100
要求:不仅内部要根据Score排序,整个List也要根据Score排序
List<Map<String, List<Map<String, Object>>>> tagsList = new ArrayList<>(); List<Map<String, Object>> resultlist1 = new ArrayList<>(); Map<String, List<Map<String, Object>>> listMap1 = new HashMap<>(); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("id", "1"); map1.put("name", "张一"); map1.put("Score", 7L); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("id", "2"); map2.put("name", "李一"); map2.put("Score", 100L); Map<String, Object> map3 = new HashMap<String, Object>(); map3.put("id", "3"); map3.put("name", "王一"); map3.put("Score", 86L); Map<String, Object> map4 = new HashMap<String, Object>(); map4.put("id", "4"); map4.put("name", "赵一"); map4.put("Score", 0L); resultlist1.add(map1); resultlist1.add(map2); resultlist1.add(map3); resultlist1.add(map4); listMap1.put("1", resultlist1); tagsList.add(listMap1); List<Map<String, Object>> resultlist2 = new ArrayList<>(); Map<String, List<Map<String, Object>>> listMap2 = new HashMap<>(); Map<String, Object> map2_1 = new HashMap<String, Object>(); map2_1.put("id", "1"); map2_1.put("name", "张二"); map2_1.put("Score", 709L); Map<String, Object> map2_2 = new HashMap<String, Object>(); map2_2.put("id", "2"); map2_2.put("name", "李二"); map2_2.put("Score", 0L); Map<String, Object> map2_3 = new HashMap<String, Object>(); map2_3.put("id", "3"); map2_3.put("name", "王二"); map2_3.put("Score", 456L); Map<String, Object> map3_4 = new HashMap<String, Object>(); map3_4.put("id", "4"); map3_4.put("name", "赵二"); map3_4.put("Score", 0L); resultlist2.add(map2_1); resultlist2.add(map2_2); resultlist2.add(map2_3); resultlist2.add(map3_4); listMap2.put("2", resultlist2); tagsList.add(listMap2); List<Map<String, Object>> resultlist3 = new ArrayList<>(); Map<String, List<Map<String, Object>>> listMap3 = new HashMap<>(); Map<String, Object> map3_1 = new HashMap<String, Object>(); map3_1.put("id", "1"); map3_1.put("name", "张三"); map3_1.put("Score", 9L); Map<String, Object> map3_2 = new HashMap<String, Object>(); map3_2.put("id", "2"); map3_2.put("name", "李三"); map3_2.put("Score", 0L); Map<String, Object> map3_3 = new HashMap<String, Object>(); map3_3.put("id", "3"); map3_3.put("name", "王三"); map3_3.put("Score", 86L); Map<String, Object> map2_4 = new HashMap<String, Object>(); map2_4.put("id", "4"); map2_4.put("name", "赵三"); map2_4.put("Score", 920L); resultlist3.add(map3_1); resultlist3.add(map3_2); resultlist3.add(map3_3); resultlist3.add(map2_4); listMap3.put("3", resultlist3); tagsList.add(listMap3); System.out.println("未排序时的tagsList:" + tagsList); //先对每一个里的Score降序排序,排序后tagsList里的每一个元素中的List<Map<String, Object>>都是有序的 for (Map<String, List<Map<String, Object>>> ins : tagsList) { for (List<Map<String, Object>> list : ins.values()) { list.sort((o1, o2) -> { Long one = Long.valueOf(o1.get("Score").toString()); Long two = Long.valueOf(o2.get("Score").toString()); return two.compareTo(one); }); } } System.out.println("对每一个Score内部降序排序后的tagsList:" + tagsList); tagsList.sort((o1, o2) -> { Long one = 0L; Long two = 0L; for (List<Map<String, Object>> v : o1.values()) { one = Long.valueOf(v.get(0).get("Score").toString()); break; } for (List<Map<String, Object>> v : o2.values()) { two = Long.valueOf(v.get(0).get("Score").toString()); break; } return two.compareTo(one); }); System.out.println("根据最内层的最大值排序后的tagsList:" + tagsList);
输出结果:
未排序时的tagsList:
[{1=[{Score=7, name=张一, id=1}, {Score=100, name=李一, id=2}, {Score=86, name=王一, id=3}, {Score=0, name=赵一, id=4}]},
{2=[{Score=709, name=张二, id=1}, {Score=709, name=张二, id=1}, {Score=456, name=王二, id=3}, {Score=0, name=赵二, id=4}]},
{3=[{Score=9, name=张三, id=1}, {Score=0, name=李三, id=2}, {Score=86, name=王三, id=3}, {Score=920, name=赵三, id=4}]}]
对每一个Score内部降序排序后的tagsList:
[{1=[{Score=100, name=李一, id=2}, {Score=86, name=王一, id=3}, {Score=7, name=张一, id=1}, {Score=0, name=赵一, id=4}]},
{2=[{Score=709, name=张二, id=1}, {Score=709, name=张二, id=1}, {Score=456, name=王二, id=3}, {Score=0, name=赵二, id=4}]},
{3=[{Score=920, name=赵三, id=4}, {Score=86, name=王三, id=3}, {Score=9, name=张三, id=1}, {Score=0, name=李三, id=2}]}]
根据最内层的最大值排序后的tagsList:
[{3=[{Score=920, name=赵三, id=4}, {Score=86, name=王三, id=3}, {Score=9, name=张三, id=1}, {Score=0, name=李三, id=2}]},
{2=[{Score=709, name=张二, id=1}, {Score=709, name=张二, id=1}, {Score=456, name=王二, id=3}, {Score=0, name=赵二, id=4}]},
{1=[{Score=100, name=李一, id=2}, {Score=86, name=王一, id=3}, {Score=7, name=张一, id=1}, {Score=0, name=赵一, id=4}]}]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。