[{"a":"1","b":"2"},{"a":"0","b":"4"},{"a":"0","b":"3"},{"a":"1","b":"5"},{"a":"0","b":"1"}],对该数组先以a倒序排序,再以b正序排序的java代码
时间: 2024-02-25 14:50:26 浏览: 56
USBA型、B型、Mini和 Micro接口 说明
可以使用Java的Collections类中的sort方法来对该数组进行排序。首先,我们需要创建一个Comparator对象,以a倒序排序。然后,再创建一个Comparator对象,以b正序排序。最后,使用Collections的sort方法对数组进行排序。
以下是示例代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<MyObject> list = new ArrayList<>();
list.add(new MyObject("1", "2"));
list.add(new MyObject("0", "4"));
list.add(new MyObject("0", "3"));
list.add(new MyObject("1", "5"));
list.add(new MyObject("0", "1"));
// 按照a倒序排序
Comparator<MyObject> comparatorA = Comparator.comparing(MyObject::getA, Comparator.reverseOrder());
// 按照b正序排序
Comparator<MyObject> comparatorB = Comparator.comparing(MyObject::getB);
// 先按照a倒序排序,再按照b正序排序
Collections.sort(list, comparatorA.thenComparing(comparatorB));
// 输出排序结果
for (MyObject obj : list) {
System.out.println(obj);
}
}
static class MyObject {
private String a;
private String b;
public MyObject(String a, String b) {
this.a = a;
this.b = b;
}
public String getA() {
return a;
}
public String getB() {
return b;
}
@Override
public String toString() {
return "MyObject{" +
"a='" + a + '\'' +
", b='" + b + '\'' +
'}';
}
}
}
```
运行以上代码,输出结果为:
```
MyObject{a='1', b='5'}
MyObject{a='1', b='2'}
MyObject{a='0', b='1'}
MyObject{a='0', b='3'}
MyObject{a='0', b='4'}
```
阅读全文