Java使用Lambda函数进行排序。

huangapple go评论66阅读模式
英文:

Java sorting with lambda function

问题

请帮忙将这个函数转换为 Lambda 函数,我在类型转换方面遇到了一些问题。帮忙一下。

Arrays.sort(arr, (item1, item2) -> {
    double cpr1 = (double) item1.value / (double) item1.weight;
    double cpr2 = (double) item2.value / (double) item2.weight;

    if (cpr1 < cpr2) {
        return 1;
    } else {
        return -1;
    }
});
英文:

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&lt;Item&gt;() {
    @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 &lt; cpr2) {
            return 1;
        } else {
            return -1;
        }
    }
});

答案1

得分: 1

我尝试了一些方法,最终找到了解决方案:

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

这将解决问题。

英文:

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

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

This will solve the issue.

答案2

得分: 0

public static void main(String[] args) {
  var arr = new Item[]{}; 
  Arrays.sort(arr, MyClass::useMySorting);
}

private static int useMySorting(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;
}
英文:
public static void main(String[] args) {
  var arr = new Item[]{}; 
  Arrays.sort(arr, MyClass::useMySorting);
}

private static int useMySorting(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 &lt; cpr2)
    return 1;
  else
    return -1;
}

huangapple
  • 本文由 发表于 2023年6月8日 16:56:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430191.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定