与Java中的稳定排序相反(不稳定?)

use*_*969 0 java sorting comparator java-stream

我需要通过其中一个参数对Java中的对象列表进行排序.这样可以正常工作,当有平局时,它会维持之前的顺序.

但是,我的目标是移植一些自己排序的丑陋代码,我必须保持相同的行为.在该算法中,它在平局的情况下反转先前的顺序.

例如,如果我想通过int对这些对象进行排序:

{ a, 1}
{ b, 2}
{ c, 1}
Run Code Online (Sandbox Code Playgroud)

我的代码返回:a,c,b

我正在移植的代码返回:c,a,b

我现在的代码是:

final Comparator<MyObj> myComparator =
    Comparator.comparingInt(MyObj::getSortWeight)
return myObjList
    .stream()
    .sorted(myComparator)
    .map(//doing some other transformations here)
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

是否有一种非hacky方式使其工作方式与旧代码相同?我不想重新发明轮子.

shm*_*sel 7

如果目标是以相反的顺序具有相等的元素,则可以在排序之前简单地反转列表:

List<MyObj> copy = new ArrayList<>(myObjList);
Collections.reverse(copy);
return copy.stream()
    .sorted(myComparator)
    .map(//doing some other transformations here)
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)