Search code examples
javasortingcomparisoncomparator

Java sorting with lambda function


Can someone please convert this function into lambda function... I am having some trouble in typecasting I guess. Help please

Arrays.sort(arr, new Comparator<Item>() {
    @Override
    public int compare(Item item1, Item item2) {
        double cpr1 = new Double((double) item1.value / (double) item1.weight);
        double cpr2 = new Double((double) item2.value / (double) item2.weight);
 
        if (cpr1 < cpr2) {
            return 1;
        } else {
            return -1;
        }
    }
});

Solution

  • I tried out few things and I finally found the solution:

    Arrays.sort(arr, (item1, item2) -> Double.compare((double) item2.value / item2.weight, (double) item1.value / item1.weight));
    

    This will solve the issue.