一个List对象,想把特定的值排在最前面进行处理

今天遇到一个需求,要把list中的某些特定的值排在最前面处理,所以就要对list进行排序,搜索了一下进行总结

首先对List<String> 根据特定的值进行排序

    List<String> list = Arrays.asList("apple", "banana", "cherry", "date", "sss", "fig");
        List<String> specificValues = Arrays.asList("fig", "date");
        // 指定的特定值
        list.sort((a, b) -> {
            if (specificValues.contains(a)) {
                // a在指定值列表中,应排在前面
                return -1;
            } else if (specificValues.contains(b)){
                // b在指定值列表中,应排在前面
                return 1;
            } else {
                // 其他情况保持不变
                return 0;
             }
        });
        System.out.println(list);

 然后对一个List对象根据特定的值进行排序

首先去写一个简单的类
@Data public static class Student{ private String name; private String orderNo; private int classNum; public Student(String name, String orderNo, int i) { this.name = name; this.orderNo = orderNo; this.classNum = classNum; } } 然后main方法进行验证     List<Student> studentList = new ArrayList<Student>(); studentList.add(new Student("xiaopang","SN005",1)); studentList.add(new Student("xiaopang","SN002",1)); studentList.add(new Student("xiaopang","SN004",1)); studentList.add(new Student("xiaopang","SN001",1)); studentList.add(new Student("xiaopang","AN003",1)); studentList.add(new Student("xiaopang","AN001",1)); studentList.add(new Student("xiaopang","AN002",1)); // SN开头的再前面排列 studentList.sort((student1, student2) -> { if (student1.getOrderNo().contains("SN") && student2.getOrderNo().contains("SN")) { return student1.getOrderNo().compareTo(student2.getOrderNo()); } else if (student1.getOrderNo().contains("SN") && !student2.getOrderNo().contains("SN")) { return -1; } else if (!student1.getOrderNo().contains("SN") && student2.getOrderNo().contains("SN")) { return 1; } else { return student1.getOrderNo().compareTo(student2.getOrderNo()); } }); studentList.forEach(e->{ System.out.println(e.toString()); });

  

 

posted @ 2023-11-07 14:19  张亮java  阅读(1929)  评论(0编辑  收藏  举报