I have below class :
我有以下课程:
public class Item {
String name;
double price;
// Getters & Setters
}
I can compare using lambda like this:
我可以像这样使用lambda进行比较:
Collections.sort(items, (Item o1, Item o2) -> {
int result = Double.valueOf(o2.getPrice()).compareTo(o1.getPrice());
if (result == 0) {
return o1.getName().compareTo(o2.getName());
}
return result;
});
I want to use method reference for comparing elements but I want to compare by name fist and then using price. How can I achieve this?
我想使用方法参考来比较元素,但我想通过名称比较然后使用价格进行比较。我怎样才能做到这一点?
Also is there a simplified way of using lambda here?
还有一种在这里使用lambda的简化方法吗?
1 个解决方案
#1
3
You can use the Comparator::comparing
and Comparator::comparingDouble
method to easily create a compartor on the fly:
您可以使用Comparator :: comparison和Comparator :: comparisonDouble方法轻松创建动态隔离专区:
List<Item> items = ...;
items.sort(Comparator.comparing(Item::getName).thenComparingDouble(Item::getPrice));
#1
3
You can use the Comparator::comparing
and Comparator::comparingDouble
method to easily create a compartor on the fly:
您可以使用Comparator :: comparison和Comparator :: comparisonDouble方法轻松创建动态隔离专区:
List<Item> items = ...;
items.sort(Comparator.comparing(Item::getName).thenComparingDouble(Item::getPrice));