通过 Stream API 按两个顺序对列表进行排序

问题描述 投票:0回答:1

我有一个类数组

Person
。我们称之为
arr_Person
Person
类的每个实例都有一个
int
优先级类型参数,可以采用值 0,1,2,3,4。

我需要通过 Stream API 获取排序后的对象列表:

  • 首先优先级=0的
    Person
    的所有实例;
  • 然后有所有优先级=4的实例,然后是3,然后是2,然后是1;

即先0,后倒序。怎么做?也就是说,我应该在排序中写什么:

Arrays.stream(arr_Person).sorted(???)

java list sorting java-stream
1个回答
1
投票

这是一个简单的比较器,可以满足您的需求。

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) {
                if (t1 == 0) {
                    return 0; //both equal doesnt really matter if swap or not
                } else {
                    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]

不过,从技术上讲,以下内容已经足够了:

                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
                }
© www.soinside.com 2019 - 2024. All rights reserved.