盘点Java中的排序操作方案

盘点Java中的排序操作方案

Comparable 接口-自然排序

  1. 类implements Comparable接口

  2. 类重写 public int compareTo(Object obj)方法

  • 如果返回值为正数,则表示当前对象(调用该方法的对象)比 obj 对象“大”;反之“小”;如果为零的话,则表示两对象相等
 public class Student implements Comparable {  
  
    private int id;  
    
    private String name;  
  
    public Student() {  
        super();  
    }  
  
    @Override  
    public int compareTo(Object obj) {  
        if (obj instanceof Student) {  
            Student stu = (Student) obj;  
            return id - stu.id;  
        }  
        return 0;  
    }  
  
    @Override  
    public String toString() {  
        return "<" + id + ", " + name + ">";  
    }  
  } 
  1. 使用 Arrays 的 sort 方法 对类的对象实例数组 进行排序

Comparator 比较器排序

法1

Arrays.sort方法的参数中增加一个匿名内部类new Comparator(){},在该Comparator中重写public int compare(Object o1, Object o2)方法,指定按xxx排序

	Arrays.sort(stus, new Comparator() {  
  
        @Override  
        public int compare(Object o1, Object o2) {  
            if (o1 instanceof Student && o2 instanceof Student) {  
                Student s1 = (Student) o1;  
                Student s2 = (Student) o2;  
                //return s1.getId() - s2.getId(); // 按Id排  
                return s1.getName().compareTo(s2.getName()); // 按姓名排  
            }  
            return 0;  
        }  
    
    });  

法2

使用TreeSet并指定匿名内部类new Comparator(){},最后把 多个要排序的对象item 添加到 TreeSet中,再打印TreeSet,即得到排序后的数据

	 Student stu1 = new Student(1, "Little");  
    Student stu2 = new Student(2, "Cyntin");  
    Student stu3 = new Student(3, "Tony");  
    Student stu4 = new Student(4, "Gemini");  
  
    SortedSet set = new TreeSet(new Comparator() {  
  
        @Override  
        public int compare(Object o1, Object o2) {  
            if (o1 instanceof Student  
                    && o2 instanceof Student) {  
                Student s1 = (Student) o1;  
                Student s2 = (Student) o2;  
                return s1.getName().compareTo(s2.getName());  
            }  
            return 0;  
        }     
    });  
    set.add(stu1);  
    set.add(stu3);   
    set.add(stu2);  
    set.add(stu4);  
    System.out.println(set);

java.util.Collections 工具类

Collections.sort(集合,匿名内部类)方式

 public class Main {  
    public static void main(String[] args) {  
        List<Person> people = new ArrayList<>();  
        // 添加一些 Person 对象到 people List ...  
  
        // 使用自定义的 Comparator 对 people List 进行排序  
        Collections.sort(people, new Comparator<Person>() {  
            @Override  
            public int compare(Person p1, Person p2) {  
                return p1.getAge() - p2.getAge(); // 按年龄升序排序  
            }  
        });  
        
        // 打印排序后的 List ...  
    }  
    }

lambda 表达式方式

Collections.sort(people, (p1, p2) -> p1.getAge() - p2.getAge());

Collections.reverse 反转排序(把一个排好顺序的集合进行反转)

int[] array = {1, 2, 3, 4, 5};  
List<Integer> list = Arrays.asList(array); // 注意:这里会返回一个固定大小的List,不支持add/remove操作  
// 由于Arrays.asList返回的List是固定大小的,所以我们不能直接反转它  
// 但可以创建一个新的ArrayList并反转它  
List<Integer> arrayList = new ArrayList<>(Arrays.asList(array));  
Collections.reverse(arrayList);  
// 如果你需要将ArrayList转回数组  
int[] reversedArray = arrayList.stream().mapToInt(Integer::intValue).toArray();

调用Comparator.reverseOrder()反转排序

 import java.util.ArrayList;  
  import java.util.Collections;  
  import java.util.Comparator;  
  import java.util.List;  
  import java.util.Random;  
  

public class SortIntegers {  

    public static void main(String[] args) {  
        List<Integer> numbers = new ArrayList<>();  
      
        // 生成10个随机整数  
        Random random = new Random();  
        for (int i = 0; i < 10; i++) {  
            numbers.add(random.nextInt(100)); // 假设随机数的范围是0到99  
        }  
      
        // 打印原始列表  
        System.out.println("原始列表:");  
        for (Integer number : numbers) {  
            System.out.print(number + " ");  
        }  
        System.out.println();  
      
        // 升序排序并打印  
        Collections.sort(numbers);  
        System.out.println("升序排序后的列表:");  
        for (Integer number : numbers) {  
            System.out.print(number + " ");  
        }  
        System.out.println();  
      
        // 降序排序并打印  
        Collections.sort(numbers, Comparator.reverseOrder());  
        System.out.println("降序排序后的列表:");  
        for (Integer number : numbers) {  
            System.out.print(number + " ");  
        }  
        System.out.println();  
    }  
}

java8stream写法

集合.sort()方法

List<Person> people = Arrays.asList(new Person("Alice", 25), new Person("Bob", 20), new Person("Charlie", 30));  
people.sort((p1, p2) -> p1.getAge() - p2.getAge()); // 按年龄升序排序  
System.out.println(people); // 输出按年龄排序后的人员列表

自定义排序(使用方法引用)

// 假设Person类有一个静态方法用于比较年龄  
  public static int compareByAge(Person p1, Person p2) {  
    return p1.getAge() - p2.getAge();  
  }  
  

List<Person> people = ...; // 初始化人员列表  
people.sort(Person::compareByAge); // 使用方法引用进行排序

排序时处理空值或特殊情况

 List<String> strings = Arrays.asList("apple", null, "banana", "", "cherry");  
strings.sort((s1, s2) -> {  
    if (s1 == null && s2 == null) return 0;  
    if (s1 == null) return 1;  
    if (s2 == null) return -1;  
    if (s1.isEmpty() && s2.isEmpty()) return 0;  
    if (s1.isEmpty()) return 1;  
    if (s2.isEmpty()) return -1;  
    return s1.compareTo(s2);  
});  
System.out.println(strings); // 输出排序后的字符串列表,空值和空字符串被放在后面

使用jdframe框架

引入依赖

 <dependency>
    <groupId>io.github.burukeyou</groupId>
    <artifactId>jdframe</artifactId>
    <version>0.0.2</version>
    </dependency>

使用内部的排序API

  • 准备集合数据
	static List<Student> studentList = new ArrayList<>();

static {
    studentList.add(new Student(1,"a","一中","一年级",11, new BigDecimal(1)));
    studentList.add(new Student(2,"a","一中","一年级",11, new BigDecimal(1)));
    studentList.add(new Student(3,"b","一中","三年级",12, new BigDecimal(2)));
    studentList.add(new Student(4,"c","二中","一年级",13, new BigDecimal(3)));
    studentList.add(new Student(5,"d","二中","一年级",14, new BigDecimal(4)));
    studentList.add(new Student(6,"e","三中","二年级",14, new BigDecimal(5)));
    studentList.add(new Student(7,"e","三中","二年级",15, new BigDecimal(5)));
}
  • 可以多重排序
	 // 等价于 order by age desc
SDFrame.read(studentList).sortDesc(Student::getAge);
//  等价于 order by age desc, level asc
SDFrame.read(studentList).sortDesc(Student::getAge).sortAsc(Student::getLevel);
// 等价于 order by age asc
SDFrame.read(studentList).sortAsc(Student::getAge);
// 使用Comparator 排序
SDFrame.read(studentList).sortAsc(Comparator.comparing(e -> e.getLevel() + e.getId()));

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ThinkPet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值