使用比较器排序(特定值除外)

时间:2019-09-13 13:54:01

标签: java comparator

我正在按值比较对象列表。但是该值应该是我的用户定义值。我有一个列表{0,qwerty} {2,abc},{4,xyz},{0,temp}。我想按第一个值排序,但我希望所有对象的末尾都为零。意味着我想对零值进行排序。我该怎么做?

main();

function main() {
    var doc = app.activeDocument;
    var page = doc.pages[0];
    var bounds = page.bounds;
    var width = RoundWithDecimal(bounds[3] - bounds[1], 3);
    var height = RoundWithDecimal(bounds[2] - bounds[0], 3);
}

function RoundWithDecimal(number, decimals){
    var multiplier = Math.pow(10,decimals);
    return Math.round(number*multiplier)/multiplier;
}

2 个答案:

答案 0 :(得分:0)

public int compare(YourSortableEntity o1, YourSortableEntity o2) {
    if(o1.getRank() == o2.getRank()) {
        //futrther logic
    } else if(o1.getRank() == 0) {
        return 1;
    } else if(o2.getRank() == 0) {
        return -1;
    } else return o1.getRank() - o2.getRank();
}

答案 1 :(得分:0)

public static void main(String[] args)
{
    YourSortableEntity e1 = new YourSortableEntity(0);
    YourSortableEntity e2 = new YourSortableEntity(2);
    YourSortableEntity e3 = new YourSortableEntity(4);
    YourSortableEntity e4 = new YourSortableEntity(0);
    YourSortableEntity e5 = new YourSortableEntity(3);
    YourSortableEntity e6 = new YourSortableEntity(0);


    List<YourSortableEntity> l = new ArrayList<>();
    l.add(e1);
    l.add(e2);
    l.add(e3);
    l.add(e4);
    l.add(e5);
    l.add(e6);

    Comparator<YourSortableEntity> myCustomComparator = new Comparator<YourSortableEntity>() {
        @Override
        public int compare(YourSortableEntity o1, YourSortableEntity o2) {
            if(o2.getRank()==0)
            {
                return -1;
            }
            else if (o1.getRank() == 0)
            {
                return 1;
            }
            return o1.getRank() - o2.getRank();
        }
    };

    Collections.sort(l, myCustomComparator);

    for (YourSortableEntity e : l)
    {
        System.out.println(e.getRank());
    }
}