zoukankan      html  css  js  c++  java
  • Java8之集合排序

    1,List<Map<String,Object>>格式

    这种排序方式有bug,如果item.get(sortField)是数字,toString()之后排序是不正确的

    //排序
            Comparator<Map<String, Object>> comparator = Comparator.comparing(item -> item.get(sortField).toString());
            if (Constant.SORT_TYPE_ASC == sortType){
                //升序
                resourceList.sort(comparator);
            }else {
                resourceList.sort(comparator.reversed());
            }

    2,List<Model>格式

    resultList.sort(Comparator.comparing(MetaDataModel::getOrder));
    dictVoList.sort(Comparator.comparingInt(DictVo::getOrder));

     3,Set<Model>格式

    public static void test2(){
    Set<Student> students = new HashSet<>();
    Student student1 = new Student(1,"李四",1);
    Student student2 = new Student(2,"张三",3);
    Student student3 = new Student(3,"王麻",2);
    students.add(student1);
    students.add(student2);
    students.add(student3);
    List<Student> studentList1 = new ArrayList<>(students);
    studentList1.sort(Comparator.comparing(Student::getAge));
    System.out.println(studentList1);
    }

    4,Set<String>格式

    public static void test3(){
            Set<String> sets = new HashSet<>();
            sets.add("aa");
            sets.add("ee");
            sets.add("cc");
            //倒序
            Set<String> treeSetDesc = new TreeSet<>((o1, o2) -> o2.compareTo(o1));
            treeSetDesc.addAll(sets);
            System.out.println(treeSetDesc);
            //升序
            Set<String> treeSetAsc = new TreeSet<>((o1, o2) -> o1.compareTo(o2));
            treeSetAsc.addAll(sets);
            System.out.println(treeSetAsc);
        }
  • 相关阅读:
    2021年4月27日 团队冲刺阶段01
    2021年4月26日
    2021年4月25日
    2021年4月24日
    2021年4月23日
    2021年4月22日
    2021年4月21日
    神奇的数列之“Last Defence ”
    经典圆交面积求解之“Intersection ”
    计蒜客第六场
  • 原文地址:https://www.cnblogs.com/cailijuan/p/10687698.html
Copyright © 2011-2022 走看看