繁体   English   中英

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

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

输入:

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

Output:

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

我应该使用什么逻辑来获得最少 function 结果?

我有一个 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;
    }
}

看起来您需要根据模数(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));
        }
    });

我通过返回解决了这个问题

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

在我使用 Collections.sort() 之后:

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

我试图使用它来按升序排列它,但它无济于事:

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

知道如何按升序获取它,这样我就不会使用Collections.reverse(sourceList);

暂无
暂无

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

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