英文:
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<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;
}
}
});
答案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) -> 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 < cpr2)
return 1;
else
return -1;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论