Java 按优先级对列表进行排序,然后将具有相同优先级的元素按相反顺序排序

Java 按优先级对列表进行排序,然后将具有相同优先级的元素按相反顺序排序,java,sorting,Java,Sorting,我想按优先级从高到低对列表进行排序。这是正确的,但我需要的是具有相同优先级的元素被反转(因为我首先需要最后添加的项)。name变量是我为快速查看原始顺序而添加的 一些代码需要澄清: myList.add(new Test(-1,"first")); myList.add(new Test(-1,"second")); myList.add(new Test(-1,"third")); myList.add(new Test(1, "fourth")); myList.add(new T

我想按优先级从高到低对列表进行排序。这是正确的,但我需要的是具有相同优先级的元素被反转(因为我首先需要最后添加的项)。name变量是我为快速查看原始顺序而添加的

一些代码需要澄清:

 myList.add(new Test(-1,"first"));
 myList.add(new Test(-1,"second"));
 myList.add(new Test(-1,"third"));
 myList.add(new Test(1, "fourth"));
 myList.add(new Test(1, "fifth"));

 public static class Test{
    private int priority;
    private String name;

    public Test(int priority, String name) {
        this.priority = priority;
        this.name = name;
    }
}
现在我这样做:

myList=Stream.of(myList).sortBy(r->-r.priority.toList()

结果是:

第四,第五,第一,第二,第三

我希望得到的结果是:

第五,第四,第三,第二,第一

我如何做这样的事情(更喜欢使用库)

你可以这样试试

编辑:我在解决方案中修复了一些东西,你应该试试

你可以这样试试


编辑:我在解决方案中修复了一些东西,你应该试试看。我不需要按名称比较任何东西。我只想根据优先级对元素进行排序,并根据它们添加到原始列表中的时间对具有相同优先级的元素进行排序(但顺序相反)。在这种情况下,您可以将t2.name.compareTo(t1.name)替换为“return 1”,在这种情况下,它应该将t2放在前面t1@PrisonMike我对代码做了一些修改,我对它有一些问题,现在它应该工作得更清晰一些:
myList.stream().sorted(Comparator.comparingit(t->t.priority).reversed().thenComparing((t1,t2)->-1)).collector(Collectors.toList())
我不需要按名称比较任何东西。我只想根据优先级对元素进行排序,并根据它们添加到原始列表中的时间对具有相同优先级的元素进行排序(但顺序相反)。在这种情况下,您可以将t2.name.compareTo(t1.name)替换为“return 1”,在这种情况下,它应该将t2放在前面t1@PrisonMike我对代码做了一些修改,我对它有一些问题,现在它应该工作得更清晰一些:
myList.stream().sorted(Comparator.comparingit(t->t.priority).reversed().thenComparing((t1,t2)->-1)).collect(Collectors.toList())
  myList.stream().sorted((t1,t2) ->{
          if (t1.priority == t2.priority)
              return -1;
          return -(Integer.compare(t1.priority, t2.priority));
      }).collect(Collectors.toList())