簡體   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