简体   繁体   English

如何在java中按function的升序排列List的项目?

[英]How to sort items of List in ascending order of function in java?

Input:输入:

["-5", "-12", "0", "20", "9", "-20", "37"]

Output: Output:

["0", "-5", "9", "-12", "-20", "20", "37"]

What logic should I use in order to get minimum of function result?我应该使用什么逻辑来获得最少 function 结果?

I have a class with function which compares 2 items (int) and returns min of them:我有一个 class 和 function,它比较 2 个项目 (int) 并返回其中的最小值:

class ListComparator implements Comparator<String> {
    @Override
    public int compare(String a, String b) {
        int intA = Integer.parseInt(a);
        int intB = Integer.parseInt(b);
        int calculatedA = calc(intA);
        int calculatedB = calc(intB);
        return (calculatedA < calculatedB) ? intA : intB;
    }

    private int calc(int x) {
        double form = Math.pow(5*x, 2) + 3;
        int result = (int) form;
        return result;
    }
}

Looks like you need to sort the array or list based on the modulus (the function Math.abs()).看起来您需要根据模数(function Math.abs())对数组或列表进行排序。

    String[] ss = {"-5", "-12", "0", "20", "9", "-20", "37"};
    List<String> strings = Arrays.asList(ss);
    Collections.sort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            int intA = Integer.parseInt(o1);
            int intB = Integer.parseInt(o2);
            return Integer.compare(Math.abs(intA), Math.abs(intB));
        }
    });

I resolved this by returning我通过返回解决了这个问题

return calculatedA > calculatedB ? -1 : (calculatedA < calculatedB) ? 1 : 0;

and after I used Collections.sort():在我使用 Collections.sort() 之后:

public void sort(List<String> sourceList) {
    Collections.sort(sourceList, new ListComparator());
    Collections.reverse(sourceList);
}

I tried to use this in order to get it in ascending order but it can't help:我试图使用它来按升序排列它,但它无济于事:

return calculatedA > calculatedB ? 1 : (calculatedA < calculatedB) ? -1 : 0;

Any idea how to get it in ascending order, so that I don't use Collections.reverse(sourceList);知道如何按升序获取它,这样我就不会使用Collections.reverse(sourceList); ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM