JAVA 集合 升序|降序|随机|去重排序

柔情只为你懂 2022-05-26 08:47 366阅读 0赞

一、说明

List排序规则可分为如下:

1.自定义排序
2.使用Collections工具类进行排序
Collections支付三种排序
A.sort()默认排序(从小到大)
B.reverse()倒序(从大到小)
C.shuffle()随机排序

List排序大体上分为如下两类:

1、List 对Integer、String等类型的List排序
2、List 对自定义对象的排序

二、示例

(一)、升序

  1. List<Integer> sortList = new ArrayList<Integer>();
  2. sortList.add(3);
  3. sortList.add(1);
  4. sortList.add(2);
  5. sortList.add(9);
  6. sortList.add(7);
  7. Collections.sort(sortList);//默认排序(从小到大)
  8. for(int i : sortList){
  9. System.out.println("默认排序(从小到大)----" + i);
  10. }

(二)、倒序

  1. List<Integer> sortList = new ArrayList<Integer>();
  2. sortList.add(3);
  3. sortList.add(1);
  4. sortList.add(2);
  5. sortList.add(9);
  6. sortList.add(7);
  7. Collections.reverse(sortList);//倒叙(从大到小)
  8. for(int i : sortList){
  9. System.out.println("倒叙(从大到小)----" + i);
  10. }

(三)、随机

  1. List<Integer> sortList = new ArrayList<Integer>();
  2. sortList.add(3);
  3. sortList.add(1);
  4. sortList.add(2);
  5. sortList.add(9);
  6. sortList.add(7);
  7. Collections.shuffle(sortList); //随机排序
  8. for(int i : sortList){
  9. System.out.println("随机排序----" + i);
  10. }

(四)、去重

  1. //set集合去重,不打乱顺序
  2. List<String> list = new ArrayList<String>();
  3. list.add("aaa");
  4. list.add("bbb");
  5. list.add("aaa");
  6. list.add("aba");
  7. list.add("aaa");
  8. Set set = new HashSet();
  9. List newList = new ArrayList();
  10. for (String cd:list) {
  11. if(set.add(cd)){
  12. newList.add(cd);
  13. }
  14. }
  15. System.out.println( "去重后的集合: " + newList);

(五)、自定义排序

  1. //自定义排序规则
  2. Map<String,Object> sortMap = new HashMap<String,Object>();
  3. sortMap.put("1", "A");
  4. sortMap.put("2", "B");
  5. sortMap.put("3", "C");
  6. sortMap.put("4", "D");
  7. sortMap.put("5", "E");
  8. sortMap.put("6", "E");
  9. sortMap.put("7", "E");
  10. sortMap.put("8", "E");
  11. sortMap.put("9", "E");
  12. sortMap.put("10", "E");
  13. sortMap.put("11", "E");
  14. sortMap.put("12", "E");
  15. sortMap.put("12", "F");
  16. List<Map<String,Object>> sortList = new ArrayList<Map<String,Object>>();
  17. sortList.sort(new Comparator<Map<String, Object>>() {
  18. @Override
  19. public int compare(Map<String, Object> o1, Map<String, Object> o2) {
  20. int randomOne = (int) (Math.random() * 10);
  21. int randomTwo = (int) (Math.random() * 10);
  22. return randomOne - randomTwo;
  23. }
  24. });
  25. sortList.add(sortMap);
  26. for (Map mps : sortList) {
  27. System.out.println(JSON.toJSON(mps));
  28. }

发表评论

表情:
评论列表 (有 0 条评论,366人围观)

还没有评论,来说两句吧...

相关阅读