Home > OS >  How to sort items of List in ascending order of function in java?
How to sort items of List in ascending order of function in java?

Time:11-23

Input:

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

Output:

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

What logic should I use in order to get minimum of function result?

I have a class with function which compares 2 items (int) and returns min of them:

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;
    }
}

CodePudding user response:

Looks like you need to sort the array or list based on the modulus (the 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));
        }
    });

CodePudding user response:

I resolved this by returning

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

and after I used 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);

  • Related