我有一个 Person 类数组。我们称之为 arr_Person。 Person 类的每个实例都有一个 int 优先级类型参数,可以取值 0,1,2,3,4。
我需要通过 Stream API 获取排序后的对象列表:
即先0,后倒序。怎么做?也就是说,我应该在排序中写什么:
Arrays.stream(arr_Person).sorted(???)
谢谢
白文章但没有找到这样的例子
这是一个简单的比较器,可以满足您的需求。
public static void main(String[] args) throws Exception {
List<Integer> ints = List.of(1, 2, 3, 4, 1, 3, 4, 2, 0, 1, 0);
Comparator<Integer> intComparator = new Comparator<Integer>() {
@Override
public int compare(Integer t0, Integer t1) {
if (t0 == 0 && t1 == 0) {
return 0; //both equal doesnt really matter if swap or not
} else if (t0 == 0) {
return -1; //first item is 0, do not swap positions
} else if (t1 == 0) {
return 1; //second item is 0, swap positions
} else {
return -(t0.compareTo(t1)); //reverse order
}
}
};
System.out.println(ints.stream().sorted(intComparator).toList());
}
代码中的注释描述了它的工作原理。它给出的输出为:
[0, 0, 4, 4, 3, 3, 2, 2, 1, 1, 1]