oracle 多重排序,Comparator 多重排序

本文详细介绍了Java中使用Comparator接口进行单条件和多条件排序的方法,包括年龄正序、价格反序以及中文名字正序、年龄正序、价格反序的排序。示例代码展示了如何自定义比较器来实现不同条件的排序,并提供了Person类的实例化和数据初始化过程。
摘要由CSDN通过智能技术生成

单条件排序

static class PersonComparator implements Comparator {

@Override

public int compare(Person o1, Person o2) {

return o1.getAge() - o2.getAge();

}

}

// 调用

Collections.sort(list, new PersonComparator());

多条件排序

static class PersonComparatorDouble implements Comparator {

@Override

public int compare(Person o1, Person o2) {

int flag = o1.getAge() - o2.getAge();

if (flag == 0) {

return o2.getPrice() - o1.getPrice();

} else {

return flag;

}

}

}

// 调用 age正序 price反序

Collections.sort(list, new PersonComparatorDouble());

中文,多条件

static class PersonComparatorThird implements Comparator {

@Override

public int compare(Person o1, Person o2) {

Comparator cmp = (Collator.getInstance(Locale.CHINA));

int flag = cmp.compare(o1.getName(), o2.getName());

if (flag == 0) {

int flag2 = o1.getAge() - o2.getAge();

if (flag2 == 0) {

return o2.getPrice() - o1.getPrice();

} else {

return flag2;

}

} else {

return flag;

}

}

}

// 调用 中文排序 name正序 age正序 price反序

Collections.sort(list, new PersonComparatorThird());

上面用到的实体类

public class Person {

private String name;

private int age;

private int price;

public Person(String name, int age) {

this.name = name;

this.age = age;

}

public Person(String name, int age, int price) {

this.name = name;

this.age = age;

this.price = price;

}

@Override

public String toString() {

return "Person[name = " + name + ",age = " + age + " price = " + price + "]";

}

// get()... set()...

}

初始化数据:

private void initData() {

list = new ArrayList();

list.add(new Person("zhang", 22, 9));

list.add(new Person("li", 80, 8));

list.add(new Person("huang", 31, 7));

list.add(new Person("bai", 8, 6));

list.add(new Person("wei", 57, 5));

list.add(new Person("huang", 31, 9));

}

以上是Comparator的用法,如果实现了Comparable接口

重写compareTo方法也可以直接调用快速对比,不过基本没见人用过

public class Person implements Comparable {

private String name;

private int age;

public Person(String name, int age) {

this.name = name;

this.age = age;

}

@Override

public String toString() {

return "Person[name = " + name + ",age = " + age + "]";

}

@Override

public int compareTo(Person person) {

return this.getAge() - person.getAge();

}

}

// 调用

Collections.sort(list_imp);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值